Python subprocess.Popen() error (No such file or directory)(Python subprocess.Popen() 错误(没有这样的文件或目录))
问题描述
我正在尝试使用 Python 函数计算文件中的行数.在当前目录中,当 os.system("ls") 找到文件时,命令 subprocess.Popen(["wc -l filename"], stdout=subprocess.PIPE代码>) 不起作用.
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.
这是我的代码:
>>> 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
推荐答案
您应该将参数作为列表传递(推荐):
You should pass the arguments as a list (recommended):
subprocess.Popen(["wc", "-l", "sorted_list.dat"], stdout=subprocess.PIPE)
否则,如果要使用整个"wc -l sorted_list.dat"字符串作为命令,则需要传递shell=True(不推荐,可以是安全隐患).
Otherwise, you need to pass shell=True if you want to use the whole "wc -l sorted_list.dat" string as a command (not recommended, can be a security hazard).
subprocess.Popen("wc -l sorted_list.dat", shell=True, stdout=subprocess.PIPE)
详细了解 shell=True 安全问题 这里.
Read more about shell=True security issues here.
这篇关于Python subprocess.Popen() 错误(没有这样的文件或目录)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python subprocess.Popen() 错误(没有这样的文件或目录)
				
        
 
            
        基础教程推荐
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
 - 修改列表中的数据帧不起作用 2022-01-01
 - 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
 - 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
 - Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
 - PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
 - PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
 - 包装空间模型 2022-01-01
 - 求两个直方图的卷积 2022-01-01
 - 在Python中从Azure BLOB存储中读取文件 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
				
				
				
				