簡體   English   中英

subprocess.Popen(): OSError: [Errno 8] python 中的 Exec 格式錯誤?

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

昨天,我編寫並運行了一個 python script ,該腳本使用 subprocess.Popen subprocess.Popen(command.split())執行shell ,其中命令是構成.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()

我的殼.sh:

  arg1=$1
  arg2=$2

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

我通過將這一行放在被調用的 shell 腳本的頂部來解決這個問題:

#!/bin/sh

這將保證系統在運行腳本時始終使用正確的解釋器。

以下聲明對我有用

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

正如@tripleee 所說,執行腳本時出現問題。 確保:

  • 將 shell 命令更改為“./my_path/my_script.sh”或“/bin/bash my_path/my_script.sh”。 如有必要,請考慮環境變量。
  • 兩個腳本都設置了執行位(chmod +x)
  • 這些文件存在於您認為它們存在的位置。 (使用 abspath 或驗證環境)
  • 文件有內容
  • 嘗試刪除並重新鍵入第一行。 我建議刪除整行,並多次按退格鍵,以防 #!

另請參閱: 為什么 '#!/usr/bin/env python' 應該比 '#!/usr/bin/python' 更正確?

如果二進制文件不打算在您的系統上運行,也會發生這種情況。

我在 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

該錯誤消息表明外部程序不是有效的可執行文件。

錯誤是因為可執行文件沒有以子進程執行的規定格式給出。

例子:

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,因為 subprocess 需要像 (mailx, ls, ping 等) 這樣的可執行命令或像 shell_command2 這樣的可執行腳本,或者你需要像這樣指定命令

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

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

我目前面臨同樣的問題。 我注意到使用shell=True參數,如 subprocess.Popen subprocess.Popen(shell_command.split() , shell=True) 可以正常工作。

建議安裝binfmt-support包,幫助系統更好的識別scipts。 無論他們是否有shebang線,它都會有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM