【问题标题】:Python subprocess call returns "command not found", Terminal executes correctlyPython 子进程调用返回“找不到命令”,终端正确执行
【发布时间】:2012-03-19 08:53:57
【问题描述】:

我正在尝试从 python 运行 gphoto2,但是没有成功。它只是返回未找到的命令。 gphoto 已正确安装,如终端中的命令正常工作。

p = subprocess.Popen(['gphoto2'], shell=True, stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT, executable='/bin/bash')

for line in p.stdout.readlines():
    print line
p.wait()

/bin/bash: gphoto2: command not found

我知道 osx 终端(应用程序)有一些有趣的地方,但是我对 osx 的了解很少。

对这个有什么想法吗?

编辑

更改了我的一些代码,出现其他错误

p = subprocess.Popen(['gphoto2'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout:
    print line


    raise child_exception
OSError: [Errno 2] No such file or directory

编辑

使用完整路径'/opt/local/bin/gphoto2'

但如果有人愿意解释使用哪个 shell 或如何登录并能够拥有相同的功能..?

【问题讨论】:

  • 你为什么不使用subprocess.check_output()或者一次输出整个东西?

标签: python shell terminal subprocess


【解决方案1】:

使用shell = True 时,subprocess.Popen 的第一个参数应该是字符串,而不是列表:

p = subprocess.Popen('gphoto2', shell=True, ...)

但是,应尽可能避免使用shell = True,因为它可能是security risk(请参阅警告)。

所以改用

p = subprocess.Popen(['gphoto2'], ...)

(当shell = False,或者shell参数被省略时,第一个参数应该是一个列表。)

【讨论】:

  • 谢谢,正确地重构了我的代码。虽然它没有让我更进一步。我已经编辑了我的帖子
  • 如果你使用gphoto2的完整路径会发生什么?
  • 在终端尝试命令which gphoto2查找完整路径。
  • 我会避免添加代码的完整路径...最好添加到os.environ['PATH'],因为不同的运行时环境可能有不同的路径
猜你喜欢
  • 2021-12-04
  • 2014-08-06
  • 2014-06-12
  • 1970-01-01
  • 1970-01-01
  • 2014-03-25
  • 1970-01-01
  • 1970-01-01
  • 2015-06-08
相关资源
最近更新 更多