【问题标题】:subprocess.run failure vs subprocess.check_call successsubprocess.run 失败与 subprocess.check_call 成功
【发布时间】:2018-02-22 05:16:04
【问题描述】:

我在通过 python 脚本启动 npm 命令时遇到问题。

来自Run npm commands using Python subprocess 我发现以下应该可以工作:

subprocess.check_call('start npm run features:chrome:server', shell=True)

确实如此(!)。

从文档 (https://docs.python.org/3/library/subprocess.html) 中,我读到 subprocess.check_call 等同于 run(..., check=True)

由于我之前使用 subprocess.run 成功启动了外部应用程序(newman),因此我尝试了以下操作:

subprocess.run("start npm run features:chrome:server", check=True)

但它最终会出现错误:

Traceback (most recent call last):
  File "test_differentiel.py", line 73, in <module>
    subprocess.run("start npm run features:chrome:server")
  File "C:\Users\a.joly\AppData\Local\Programs\Python\Python36-32\lib\subprocess.py", line 403, in run
    with Popen(*popenargs, **kwargs) as process:
  File "C:\Users\a.joly\AppData\Local\Programs\Python\Python36-32\lib\subprocess.py", line 707, in __init__
    restore_signals, start_new_session)
  File "C:\Users\a.joly\AppData\Local\Programs\Python\Python36-32\lib\subprocess.py", line 990, in _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] Le fichier spécifié est introuvable

知道为什么我不能使用 subprocess.run 吗? (顺便说一句,也不是 check_output ...)

【问题讨论】:

  • 从错误消息中,您忘记在subprocess.run() 中添加shell=True,因此假定完整字符串'start npm run features:chrome:server' 是目标可执行文件。而且我认为可以安全地假设该文件不存在...
  • 好点,我没有设置shell=True,我们试试吧...!伟大的 !有用 ! :) 谢谢。
  • shell=True 拆分参数字符串(通过将其传递给 shell)。 shell=False 尝试运行名为 'start npm run features:chrome:server' 的可执行文件(带有空格的完整字符串,而不仅仅是 start.exe)。

标签: python node.js subprocess


【解决方案1】:

正确的执行是 subprocess.run(['start', 'npm', 'run', 'features:chrome:server'], check=True)

subprocess.check_call('start npm run features:chrome:server', shell=True) 有效,因为您调用了 shell。您可以找到更多信息here

subprocess.run("start npm run features:chrome:server", check=True, shell=True) 也应该可以工作。

【讨论】:

  • 这实际上是行不通的,shell=True 才是重点……虽然语法可能更 Pythonic (?)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-14
相关资源
最近更新 更多