subprocess.check_output失败,错误127

问题描述 投票:5回答:4

我试图从我的python应用程序调用外部程序,但它显示没有输出并失败,错误127.从命令行执行命令工作正常。 (我在正确的工作目录中)

def buildContris (self, startUrl, reportArray):
    urls = []

    for row in reportArray:
        try:
            url = subprocess.check_output(["casperjs", "casper.js", startUrl, row[0]], shell=True)
            print (url)
            urls.append(url)
            break
        except subprocess.CalledProcessError as e:
            print ("Error: " + str(e.returncode) + " Output:" + e.output.decode())          

    return urls

每个循环输出以下错误:(我也检查过e.cmd。它是正确的,但很长,所以我在这个例子中省略了它)

Error: 127 Output: 

解:

以下代码有效

app = subprocess.Popen(["./casperjs/bin/casperjs", "casper.js", startUrl, row[0]], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env = {"PATH" : "/usr/local/bin/:/usr/bin"}, universal_newlines=True)
app.wait()
out, errs = app.communicate()
python subprocess
4个回答
3
投票

尝试在subprocess.check_output()调用中添加casperjs的完整路径。

编辑:回答你的第二个问题。我在iPad上对格式化表示歉意。我认为您应该尝试使用Popen而不是check_output,以便您可以指定环境变量:

p = subprocess.Popen(["/path/to/casperjs", "casper.js", startUrl, row[0]], env={"PATH": "/path/to/phantomjs"})
url, err = p.communicate()

0
投票

shell=True改变了args调用check_output()中第一个参数(from the docs)的解释:

在Unix上使用shell = True,...如果args是一个序列,则第一个项指定命令字符串,任何其他项将被视为shell本身的附加参数。也就是说,Popen相当于:

Popen(['/bin/sh', '-c', args[0], args[1], ...])

退出状态127可能意味着shell没有找到casperjs程序或casperjs本身退出该代码。

要修复代码:删除shell=True并指定casperjs程序的完整路径,例如:

url = check_output(["./casperjs", "casper.js", startUrl, row[0]])

0
投票

尝试以这种方式明确添加路径。如果要调用的文件位于同一路径中(如果不是,则更改__file__):

cwd=os.path.dirname(os.path.realpath(__file__))
a  = subprocess.check_output(["./casper.js", startUrl, row[0]],cwd=cwd,shell=True)

0
投票

如果你在macOS上遇到这种废话:不要使用别名。失去了半天。所以,改变:

subprocess.check_output(
    "scribus-ng -g -ns -py {0} {1}".format(script_path, id),
    stderr=subprocess.STDOUT,
    shell=True)

subprocess.check_output(
    "/Applications/Scribus.app/Contents/MacOS/Scribus -g -ns -py {0} {1}".format(script_path, id),
    stderr=subprocess.STDOUT,
    shell=True)
© www.soinside.com 2019 - 2024. All rights reserved.