2011-01-29 115 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完成

相关问题