2011-01-29 118 views
30
import subprocess 
retcode = subprocess.call(["/home/myuser/go.sh", "abc.txt", "xyz.txt"]) 

當我運行這兩條線,將我做的正是這種?:這是在Python中運行shell腳本的正確方法嗎?

/home/myuser/go.sh abc.txt xyz.txt 

爲什麼會出現這個錯誤?但是當我正常運行go.sh時,我沒有得到那個錯誤。

File "/usr/lib/python2.6/subprocess.py", line 480, in call 
    return Popen(*popenargs, **kwargs).wait() 
    File "/usr/lib/python2.6/subprocess.py", line 633, in __init__ 
    errread, errwrite) 
    File "/usr/lib/python2.6/subprocess.py", line 1139, in _execute_child 
    raise child_exception 
OSError: [Errno 8] Exec format error 
+7

請問你的shell腳本有正確的hashbang? – William 2011-01-29 01:43:06

+1

你有沒有解決過這個問題? – Johnsyweb 2013-05-10 02:06:06

回答

1

是的,這是完全正常的,如果你正在做的是調用shell腳本,等待它完成,並收集它的退出狀態,同時讓其標準輸入,標準輸出和標準錯誤從你的Python繼承處理。如果你需要對這些因素有更多的控制,那麼你只需要使用更一般的subprocess.Popen,否則你所擁有的就沒有問題。

+1

你能告訴我爲什麼我得到這個錯誤:OSError:[Errno 8]執行格式錯誤。當我通常運行它會很好。 – TIMEX 2011-01-29 02:38:44

0

是的,這是執行的東西的首選方法..

因爲你是將所有參數傳遞通過一個數組(將GOR一個exec()一起使用 - 風格調用內部),而不是作爲一個參數字符串由殼評估它也是非常安全的,因爲注入shell命令是不可能的。

+0

你能告訴我爲什麼我得到這個錯誤:OSError:[Errno 8]執行格式錯誤。當我通常運行它會很好。 – TIMEX 2011-01-29 01:34:53

33

OSError: [Errno 8] Exec format error

這是操作系統在嘗試運行/home/myuser/go.sh時報告的錯誤。

它在我看來像是shebang(#!)行go.sh是無效的。

下面是從外殼,但不運行從Popen一個示例腳本:

#\!/bin/sh 
echo "You've just called $0 [email protected]" 

從第一行刪除\解決了這個問題。

11

更改代碼如下:

retcode = subprocess.call(["/home/myuser/go.sh", "abc.txt", "xyz.txt"], shell=True,) 

通知 「殼=真」

來源:http://docs.python.org/library/subprocess.html#module-subprocess

On Unix, with shell=True: If args is a string, it specifies the command string to execute through the shell. This means that the string must be formatted exactly as it would be when typed at the shell prompt.

1

我剛剛在Mac OS這個錯誤,而試圖調用一個使用subprocess.call的單行腳本。從命令行調用腳本時腳本運行良好。在添加shebang線#!/usr/bin/env sh後,它也通過subprocess.call運行良好。

它的出現,而殼具有文本文件默認執行標記爲可執行,subprocess.Popen沒有。

2

我最近就遇到了這個問題,一個腳本,它是這樣的:

% cat /tmp/test.sh 
           <-- Note the empty line 
#!/bin/sh 
mkdir /tmp/example 

腳本運行在命令行,但是當通過

執行與

OSError: [Errno 8] Exec format error 

失敗

subprocess.Popen(['/tmp/test.sh']).communicate() 

(該溶液,當然,是去除空線)。

1
In :call?? 
Signature: call(*popenargs, **kwargs) 
Source: 
def call(*popenargs, **kwargs): 
    """Run command with arguments. Wait for command to complete, then 
    return the returncode attribute. 

    The arguments are the same as for the Popen constructor. Example: 

    retcode = call(["ls", "-l"]) 
    """ 
    return Popen(*popenargs, **kwargs).wait() 
File:  /usr/lib64/python2.7/subprocess.py 
Type:  function 

的調用只是調用POPEN,使用wait()方法等待popenargs完成

相關問題