当使用字符串作为参数调用命令时,subprocess.Popen() 出现错误(没有此文件或目录)
- 2025-03-12 08:54:00
- admin 原创
- 30
问题描述:
我正在尝试使用 Python 函数计算文件中的行数。在当前目录中,当os.system("ls")
找到文件时,命令subprocess.Popen(["wc -l filename"], stdout=subprocess.PIPE
) 不起作用。
这是我的代码:
>>> 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
解决方案 1:
您应该将参数作为列表传递(推荐):
subprocess.Popen(["wc", "-l", "sorted_list.dat"], stdout=subprocess.PIPE)
shell=True
否则,如果您想使用整个"wc -l sorted_list.dat"
字符串作为命令,则需要传递(不推荐,可能存在安全隐患)。
subprocess.Popen("wc -l sorted_list.dat", shell=True, stdout=subprocess.PIPE)
在此处阅读有关shell=True
安全问题的更多信息。
在这种情况下,要将命令用作整个字符串并避免安全问题,shell=True
可以使用shlex
import subprocess
import shlex
command = "wc -l sorted_list.dat"
subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE)
解决方案 2:
发生该错误的原因是您试图运行一个名为 的命令wc -l sorted_list.dat
,也就是说,它正在尝试查找一个名为 的文件"/usr/bin/wc -l sorted dat"
。
拆分你的论点:
["wc", "-l", "sorted_list.dat"]
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD