subprocess.Popen(): OSError: [Errno 8] Exec format error in python?

前端 未结 7 2002
余生分开走
余生分开走 2020-12-06 09:07

Yesterday, I wrote and ran a python script which executes a shell using subprocess.Popen(command.split()) where command is string whic

相关标签:
7条回答
  • 2020-12-06 09:25

    The error message suggests that the external program is not a valid executable.

    0 讨论(0)
  • 2020-12-06 09:26

    As @tripleee said, there is an issue executing your script. Make sure:

    • Change the shell command to "./my_path/my_script.sh" or "/bin/bash my_path/my_script.sh". Account for environment variables, if necessary.
    • Both scripts have execute bit set (chmod +x)
    • The files exist at the location you think they do. (Use abspath or verify environment)
    • The files have contents
    • Try removing and re-typing the first line. I recommend killing the whole line, and hitting backspace several times in case there's a non-printable character before the #!

    See also: Why is '#!/usr/bin/env python' supposedly more correct than just '#!/usr/bin/python'?

    0 讨论(0)
  • 2020-12-06 09:29

    Following statement worked for me

    subprocess.Popen(['sh','my_script.sh'])

    0 讨论(0)
  • 2020-12-06 09:29

    It is recommended to install the package binfmt-support to help the system better recognize the scipts. It helps regardless of whether they have a shebang line.

    0 讨论(0)
  • 2020-12-06 09:37

    The error is because the executables are not given in the prescribed format for subprocess to execute it.

    example:

    shell_command1 = r"/path/to/executable/shell/file"
    
    shell_command2 = r"./path/to/executable/shell/file"
    

    subprocess.call(shell_command1) or subprocess.Popen(shell_command1) will not be able to run shell_command1 because subprocess needs an executable command like (mailx, ls, ping, etc.) or executable script like shell_command2 or you need to specify command like this

    subprocess.call(["sh", shell_command1])
    subprocess.Popen(["sh", shell_command1])
    

    but however, you can use os.system() or os.Popen() as well

    0 讨论(0)
  • 2020-12-06 09:38

    I solved this by putting this line at the top of the called shell script:

    #!/bin/sh

    That will guarantee that the system always uses the correct interpreter when running your script.

    0 讨论(0)
提交回复
热议问题