Python OSError:[Errno 2]没有这样的文件或目录错误

时间:2018-10-21 13:01:07

标签: python linux operating-system subprocess call

我在通过python在Linux上运行OS命令时遇到了麻烦(我过去花了很多时间)

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

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 venv,也许以某种方式影响了问题。

我试图在linux上运行的ANY命令发生错误... 似乎是一个非常普遍的问题。

任何人都知道哪里出了问题?

1 个答案:

答案 0 :(得分:0)

由于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>