【问题标题】:Cannot make consecutive calls with subprocess无法使用子进程进行连续调用
【发布时间】:2012-07-26 20:50:31
【问题描述】:

我在使用多个子进程调用时遇到问题。

这两个工作正常:

subprocess.call(["gmake", "boot-tilera"], cwd="/home/ecorbett/trn_fp")
p = subprocess.Popen(["gmake", "run-tilera"], stdout=subprocess.PIPE, cwd="/home/ecorbett/trn_fp")

但是,当我尝试在之后直接运行此调用时出现错误:

time.sleep(10)
subprocess.call(["./go2.sh"], cwd="/home/ecorbett/trn_fp/kem_ut")

我在那里添加了睡眠,因为我需要几秒钟才能运行“./go2.sh”程序。不知道是不是这个问题。

有什么建议吗?

【问题讨论】:

  • OSError: [Errno 8] 执行格式错误
  • 你能从命令行运行 ./go2.sh 吗?如果是这样,请尝试将 shell=True 作为参数添加到您的 subprocess.call()。
  • 它从命令行工作。我会试试的。但是这个“subprocess.call(["gmake", "boot-tilera"], cwd="/home/ecorbett/trn_fp")" 在没有 "shell=True" 参数的情况下可以正常工作
  • 成功了!我想知道为什么我需要将它添加到这个命令而不是另一个?
  • go2.sh"/home/ecorbett/trn_fp/kem_ut" 里面吗? cwd 参数设置 Python 执行脚本的位置,而不是 Python 查找脚本的位置。 (docs)

标签: python subprocess


【解决方案1】:

您的 shell 脚本在命令行上运行的一个可能原因是 shebang 行没有正确编写(或根本没有编写)。查看脚本可以从命令行运行但不能作为 Python 子进程运行的示例:Is this the right way to run a shell script inside Python?

如果您的 shell 脚本没有指定 shebang 行,它可以从命令行运行,因为在您的环境中设置了 $SHELL 并且脚本将其作为默认设置。从 python 子进程运行时,python 不知道它是什么,并以OSError: [Errno 8] Exec format error 失败。 subprocess.call()gmake 有效,因为它是二进制程序而不是 shell 脚本。使用参数shell=True 给出了一个指令,可以像在shell 中一样解释该参数。

但是,在 subprocess.call() 中使用 shell=True 时要小心,因为在某些情况下它可能不安全:subprocess Python docs

【讨论】:

    猜你喜欢
    • 2022-11-05
    • 1970-01-01
    • 2013-06-22
    • 2013-01-20
    • 2019-06-24
    • 1970-01-01
    • 2011-08-10
    • 1970-01-01
    • 2021-01-13
    相关资源
    最近更新 更多