Python subprocess.Popen() 错误(没有那个文件或目录)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30010939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 07:50:00  来源:igfitidea点击:

Python subprocess.Popen() error (No such file or directory)

pythonsubprocesssystempopen

提问by user2105632

I am trying to count the number of lines in a file using Python functions. Within the current directory, while os.system("ls")finds the file, the command subprocess.Popen(["wc -l filename"], stdout=subprocess.PIPE) does not work.

我正在尝试使用 Python 函数计算文件中的行数。在当前目录中,os.system("ls")找到文件时,命令subprocess.Popen(["wc -l filename"], stdout=subprocess.PIPE) 不起作用。

Here is my code:

这是我的代码:

>>> import os
>>> import subprocess
>>> os.system("ls")
sorted_list.dat
0
>>> p = subprocess.Popen(["wc -l sorted_list.dat"], stdout=subprocess.PIPE)File "<stdin>", line 1, in <module>
File "/Users/a200/anaconda/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
File "/Users/a200/anaconda/lib/python2.7/subprocess.py", line 1335, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

采纳答案by bakkal

You should pass the arguments as a list (recommended):

您应该将参数作为列表传递(推荐):

subprocess.Popen(["wc", "-l", "sorted_list.dat"], stdout=subprocess.PIPE)

Otherwise, you need to pass shell=Trueif you want to use the whole "wc -l sorted_list.dat"string as a command (not recommended, can be a security hazard).

否则,shell=True如果要将整个"wc -l sorted_list.dat"字符串用作命令,则需要通过(不推荐,可能存在安全隐患)。

subprocess.Popen("wc -l sorted_list.dat", shell=True, stdout=subprocess.PIPE)

Read more about shell=Truesecurity issues here.

在此处阅读有关shell=True安全问题的更多信息。

回答by Antti Haapala

The error occurs because you are trying to run a command named wc -l sorted_list.dat, that is, it is trying to find a filenamed like "/usr/bin/wc -l sorted dat".

发生该错误是因为您正在尝试运行名为 的命令wc -l sorted_list.dat,也就是说,它正在尝试查找名为 like的文件"/usr/bin/wc -l sorted dat"

Split your arguments:

拆分你的论点:

["wc", "-l", "sorted_list.dat"]