windows 将带有通配符的参数传递给 Python 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/405652/
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
Passing arguments with wildcards to a Python script
提问by Kiv
I want to do something like this:
我想做这样的事情:
c:\data\> python myscript.py *.csv
and pass all of the .csv files in the directory to my python script (such that sys.argv
contains ["file1.csv", "file2.csv"]
, etc.)
并将目录中的所有 .csv 文件传递给我的 python 脚本(例如sys.argv
包含["file1.csv", "file2.csv"]
等)
But sys.argv
just receives ["*.csv"]
indicating that the wildcard was not expanded, so this doesn't work.
但sys.argv
只是收到["*.csv"]
指示通配符未扩展的指示,因此这不起作用。
I feel like there is a simple way to do this, but can't find it on Google. Any ideas?
我觉得有一种简单的方法可以做到这一点,但在谷歌上找不到。有任何想法吗?
回答by Vinko Vrsalovic
You can use the glob module, that way you won't depend on the behavior of a particular shell (well, you still depend on the shell not expanding the arguments, but at least you can get this to happen in Unix by escaping the wildcards :-) ).
您可以使用 glob 模块,这样您就不会依赖于特定 shell 的行为(好吧,您仍然依赖于不扩展参数的 shell,但至少您可以通过转义通配符在 Unix 中实现这一点:-) )。
from glob import glob
filelist = glob('*.csv') #You can pass the sys.argv argument
回答by Ned Batchelder
In Unix, the shell expands wildcards, so programs get the expanded list of filenames. Windows doesn't do this: the shell passes the wildcards directly to the program, which has to expand them itself.
在 Unix 中,shell 扩展通配符,因此程序获得扩展的文件名列表。Windows 不会这样做:shell 将通配符直接传递给程序,程序必须自行扩展它们。
Vinko is right: the glob module does the job:
Vinko 是对的:glob 模块完成了这项工作:
import glob, sys
for arg in glob.glob(sys.argv[1]):
print "Arg:", arg