【问题标题】:Python OSError: [Errno 2] No such file or directory ERRORPython OSError: [Errno 2] No such file or directory 错误
【发布时间】:2019-03-25 17:10:10
【问题描述】:

我在通过 python 在 Linux 上运行操作系统命令时遇到了麻烦(过去我做了很多时间)

我正在尝试使用subprocess 模块运行一个简单的操作系统命令:

def test_func():
    cmd = 'mkdir /tmp/test_dir'
    res = subprocess.Popen(cmd, stdout=subprocess.PIPE).stdout.read()

我收到了这个错误

Traceback (most recent call last):
  File "/Volumes/fiverr_dev/fiverr-bi/apps/apis/api_acq_bing_reports.py", line 92, in <module>
    acquisition_reports.test_func()
  File "/Volumes/fiverr_dev/fiverr-bi/apps/etls/acquisition_reports.py", line 177, in test_func
    res = subprocess.Popen(cmd, stdout=subprocess.PIPE).stdout.read()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

这突然开始发生。我一直在处理 python venvs,也许它以某种方式影响了这个问题。

我尝试在 linux 上运行的任何命令都会发生错误... 这似乎是一个非常普遍的问题。

谁知道哪里出了问题?

【问题讨论】:

  • 为什么回溯与你的代码不匹配?
  • 我尝试了几个版本。 subprocess.Popen(cmd, stdout=subprocess.PIPE).stdout.read()subprocess.call(shlex.split(cmd)) [我在主线程中修复了代码]

标签: python linux operating-system subprocess call


【解决方案1】:

当 python 试图在下面进行以下操作时,您会遇到错误。

(ins)-> cmd='mkdir /tmp/hello'
(ins)-> "$cmd"
-bash: mkdir /tmp/hello: No such file or directory

在python中使用shlex.split(cmd)

In [13]: cmd = 'mkdir /tmp/hello'

In [14]: args = shlex.split(cmd)

In [15]: subprocess.Popen(args)
Out[15]: <subprocess.Popen at 0x10e1f74e0>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-07
    • 2017-07-05
    • 2018-11-20
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    相关资源
    最近更新 更多