Python 的子进程模块从 Unix shell 返回不同的结果 [英] Python's subprocess module returning different results from Unix shell
问题描述
我正在尝试使用 python 获取目录中的 CSV 文件列表.这在 unix 中真的很容易:
ls -l *.csv
而且,可以预见的是,我在我的目录中得到了以 .csv 结尾的文件列表.但是,当我使用 Subprocess 模块尝试 Python 等效项时:
<预><代码>>>>将子进程导入为 sp>>>sp.Popen(["ls", "-l", "*.csv"], stdout = sp.PIPE)<subprocess.Popen 对象在 0xb780e90c>>>>ls: 无法访问 *.csv: 没有那个文件或目录有人可以解释一下这是怎么回事吗?
编辑:添加 shell = True
可消除错误,但我得到的不是仅包含 CSV 文件的列表,而是包含 all 目录中的文件.
如果你想让它像在 shell 中那样表现,你需要传递 shell=True
(你的里程可能在这里有所不同,取决于您的系统和外壳).在您的情况下,问题在于当您执行 ls -l *.csv
时,shell 正在评估 * 的含义,而不是 ls
.(ls
只是格式化您的结果,但 shell 已经完成了确定哪些文件与 *.csv
匹配的繁重工作).子进程使 ls
按字面意思处理 *.csv
,并查找具有该特定名称的文件,当然没有任何文件(因为这是一个很难创建的文件名)).
您真正应该做的是使用 os.listdir
并自己过滤名称.
I'm trying to get a list of the CSV files in a directory with python. This is really easy within unix:
ls -l *.csv
And, predictably, I get a list of the files that end with .csv in my directory. However, when I attempt the Python equivalent using the Subprocess module:
>>> import subprocess as sp
>>> sp.Popen(["ls", "-l", "*.csv"], stdout = sp.PIPE)
<subprocess.Popen object at 0xb780e90c>
>>> ls: cannot access *.csv: No such file or directory
Can somebody please explain what's going on?
Edit: Adding shell = True
removes the error, but instead of getting a list of just CSV files, I get a list of all the files in the directory.
If you want it to behave as it does at the shell, you need to pass shell=True
(your mileage may vary here, depending on your system and shell). In your case the problem is that when you do ls -l *.csv
, the shell is evaluating what * means, not ls
. (ls
is merely formatting your results, but the shell has done the heavy lifting to determine what files match *.csv
). Subprocess makes ls
treat *.csv
literally, and look for a file with that specific name, which of course there aren't any (since that's a pretty hard filename to create).
What you really should be doing is using os.listdir
and filtering the names yourself.
这篇关于Python 的子进程模块从 Unix shell 返回不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!