【问题标题】:Command works in shell but not in subprocess命令在 shell 中有效,但在子进程中无效
【发布时间】:2019-07-30 21:24:47
【问题描述】:

我正在尝试使用 python subprocess 包运行命令。我已将编译后的可执行文件的路径添加到我在 Ubuntu 机器上的PATH

当我这样做时,它起作用了

myexecutable input_file output_file

当我这样做时,它起作用了

import subprocess
import shlex

cmd = '/path/to/my/myexecutable input_file output_file'
subprocess.Popen(shlex.split(cmd))

这是踢球者。 当我这样做时,它不起作用

import subprocess
import shlex

cmd = 'myexecutable input_file output_file'
subprocess.Popen(shlex.split(cmd))

它给了我:

OSError                                   Traceback (most recent call last)
<ipython-input-4-8f5c3da8b0a3> in <module>()
----> 1 subprocess.call(shlex.split(cmd))

/home/me/miniconda3/envs/mypy2/lib/python2.7/subprocess.pyc in call(*popenargs, **kwargs)
    170     retcode = call(["ls", "-l"])
    171     """
--> 172     return Popen(*popenargs, **kwargs).wait()
    173
    174

/home/me/miniconda3/envs/mypy2/lib/python2.7/subprocess.pyc in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags)
    392                                 p2cread, p2cwrite,
    393                                 c2pread, c2pwrite,
--> 394                                 errread, errwrite)
    395         except Exception:
    396             # Preserve original exception in case os.close raises.

/home/me/miniconda3/envs/mypy2/lib/python2.7/subprocess.pyc in _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, to_close, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite)
   1045                         raise
   1046                 child_exception = pickle.loads(data)
-> 1047                 raise child_exception
   1048
   1049

OSError: [Errno 2] No such file or directory

什么给了?

【问题讨论】:

  • subprocess 的两种使用方式到底有什么区别?我瞎了吗?它们在我看来是一样的......
  • 你的作品/不作品看起来一模一样。
  • 它们是相同的。他试图欺骗我们 b*****d 哈哈
  • 哎呀。让我解决这个问题
  • 这两种方式完全相同。一个有绝对路径,另一个没有——我怀疑这就是为什么一个有效而另一个无效(因为一个相对于当前工作目录)。

标签: python linux python-2.7 subprocess


【解决方案1】:

无论您使用什么 shell(以及 subprocess.Popen(..., shell=True),但附带一些警告)都会根据 PATH 环境变量计算出实际的可执行文件。

subprocess.Popen() 本身不会。在 UNIX 系统上解决此问题(即进行路径查找)的一种流行方法是使用广泛可用的 /usr/bin/env 工具,它执行相同的扩展,即

subprocess.Popen(['/usr/bin/env', 'mytool', 'hurr', 'durr'])

但这不适用于 Windows。

最好的方法是自己查找,即找出可执行文件的完整路径并将其传递给subprocess.Popen() - os.path.realpath() 可能是你的朋友。

【讨论】:

  • 您的回答令人困惑。我认为您只需要说“myexecutable”不在路径中。使用 env 对他没有任何帮助。
  • 但是popen本身不会做路径扩展。
  • 哦。就像我说的,你的措辞令人困惑:)
  • @MK。现在好点了吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 2018-08-27
  • 2018-06-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多