use*_*632 19 python subprocess system popen
我试图使用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
Run Code Online (Sandbox Code Playgroud)
bak*_*kal 35
您应该将参数作为列表传递(推荐):
subprocess.Popen(["wc", "-l", "sorted_list.dat"], stdout=subprocess.PIPE)
Run Code Online (Sandbox Code Playgroud)
否则,shell=True如果要将整个"wc -l sorted_list.dat"字符串用作命令,则需要传递(不推荐,可能存在安全隐患).
subprocess.Popen("wc -l sorted_list.dat", shell=True, stdout=subprocess.PIPE)
Run Code Online (Sandbox Code Playgroud)
了解更多关于shell=True安全问题在这里.
发生错误是因为您正在尝试运行名为的命令wc -l sorted_list.dat,也就是说,它正在尝试查找名为like 的文件"/usr/bin/wc -l sorted dat"。
拆分您的参数:
["wc", "-l", "sorted_list.dat"]
Run Code Online (Sandbox Code Playgroud)