【问题标题】:subprocess: FileNotFound子进程:FileNotFound
【发布时间】:2016-05-04 21:57:08
【问题描述】:

谁能给我解释一下这个错误:

>>> def j():
...     import subprocess
...     print(subprocess.Popen(['command', '-v', 'nmcli'],     stdout=subprocess.PIPE, stderr=subprocess.PIPE))
... 
>>> j()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in j
File "/usr/lib/python3.4/subprocess.py", line 859, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.4/subprocess.py", line 1457, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'command'

我尝试将字符串作为列表,它不会改变任何东西。

【问题讨论】:

标签: python python-3.x subprocess command


【解决方案1】:

FileNotFoundError: [Errno 2] 没有这样的文件或目录:'command'

command 是一个内置的 shell。 subprocess.Popen 默认不运行 shell。

要运行 shell,请传递 shell=True:

>>> import subprocess
>>> subprocess.check_output('command -v python', shell=True)
b'/usr/bin/python\n'

要查找可执行文件的完整路径,您可以use shutil.which() instead:

>>> import shutil
>>> shutil.which('python')
'/usr/bin/python'

【讨论】:

  • 我实际上尝试了将 shell 设置为 True 的 Popen,但它返回了 2 个空的 'b' 字符串。谢谢你的shutil 提示,我从来没有想过这个:现在我会的!再次感谢!
猜你喜欢
  • 2018-04-16
  • 2013-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-19
相关资源
最近更新 更多