shell 子进程.Popen():操作错误:[Errno 8] python中的Exec格式错误?

dy2hfwbg  于 2023-01-21  发布在  Shell
关注(0)|答案(8)|浏览(178)

昨天,我编写并运行了一个python script,它使用subprocess.Popen(command.split())来执行shell,其中command是字符串,它构成了.sh脚本及其参数。这个脚本在昨天之前工作正常。今天,我运行了同样的脚本,现在我不断地遇到这个错误。

p=subprocess.Popen(shell_command.split())
File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child
raise child_exception
OSError: [Errno 8] Exec format error

我知道以前有人问过类似的问题,但在我的情况下,我尝试了所有无法解决我的目的的方法。使用shell=True不起作用,因为我的shell脚本调用另一个shell脚本,在此之前必须设置一些环境才能运行该脚本。我严重陷入了这种困境。我只重新启动了系统一次。我使用的是ubuntu 12.04

    • 编辑:**
import subprocess
 import os
 import sys

 arg1=sys.argv[1]
 arg2=sys.argve[2]

 shell_command = 'my_path/my_shell.sh ' + arg1 + ' '+ arg2
 P = subprocess.Popen(shell_command.split())
 P.wait()
    • 我的 shell . sh:**
arg1=$1
  arg2=$2

  cd $TOP
  setup the environment and run shell script
  build the kernel ...
  execute shell command .....
zbwhf8kr

zbwhf8kr1#

我通过在调用的shell脚本的顶部添加以下代码行来解决这个问题:
#!/bin/sh
这将保证系统在运行脚本时始终使用正确的解释器。

ht4b089n

ht4b089n2#

以下语句对我有效
subprocess.Popen(['sh','my_script.sh'])

fnvucqvd

fnvucqvd3#

错误消息表明外部程序不是有效的可执行文件。

bzzcjhmw

bzzcjhmw4#

正如@tripleee所说,执行脚本时出现问题。请确保:

  • 将shell命令更改为“./我的路径/我的脚本. sh”或“/bin/bash我的路径/我的脚本. sh”。如有必要,说明环境变量。
  • 两个脚本都设置了执行位(chmod +x)
  • 文件存在于您认为它们存在的位置。(使用abspath或验证环境)
  • 这些文件包含
  • 尝试删除并重新键入第一行。我建议删除整行,并按几次退格键,以防在#之前有一个不可打印的字符!

另请参阅:Why is '#!/usr/bin/env python' supposedly more correct than just '#!/usr/bin/python'?

qgelzfjb

qgelzfjb5#

如果二进制文件不打算在您的系统上运行,也可能发生这种情况。
我在OSX上,但是我运行的二进制文件并不适用于OSX,正如我在使用file path/to/binary时所看到的:

webui/bin/wkhtmltopdf: ELF 64-bit LSB executable, x86-64, version 1 (GNU/Linux), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.18, BuildID[sha1]=b6566a9e44c43a0eebf18d8c1dc6cb616801a77e, stripped
sg3maiej

sg3maiej6#

错误是因为可执行文件没有以指定的格式提供给子进程来执行它。
示例:

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

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

subprocess.call(shell_command1)subprocess.Popen(shell_command1)将无法运行shell_command1,因为子进程需要可执行命令(如mailx、ls、ping等)或可执行脚本(如shell_command2),或者您需要指定如下命令

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

但是,您也可以使用os.system()os.Popen()

m3eecexj

m3eecexj7#

我目前也面临着同样的问题。我注意到使用shell=True参数,如subprocess.Popen(shell_command.split(),shell=True)的工作原理与预期相同。

5jvtdoz2

5jvtdoz28#

建议安装binfmt-support包,帮助系统更好的识别scipts,无论scipts是否有shebang行都有帮助。

相关问题