简体   繁体   English

将带有通配符的 arguments 传递给 Python 脚本

[英]Passing arguments with wildcards to a Python script

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?有任何想法吗?

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

In Unix, the shell expands wildcards, so programs get the expanded list of filenames.在 Unix 中,shell 扩展通配符,因此程序获得扩展的文件名列表。 Windows doesn't do this: the shell passes the wildcards directly to the program, which has to expand them itself. 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

If your script is a utility, I suggest you to define a function like this in your .bashrc to call it in a directory:如果您的脚本是一个实用程序,我建议您在.bashrc定义一个这样的函数以在目录中调用它:

myscript() {
   python /path/myscript.py $@ 
}

Then the whole list is passed to your python and you can process them like:然后整个列表传递给你的python,你可以像这样处理它们:

for _file in sys.argv[1:]:
    # do something on file

If you have multiple wildcard items passed in (for eg: python myscript.py *.csv *.txt ) then, glob(sys.argv[1] may not cut it. You may need something like below.如果您传入了多个通配符项目(例如: python myscript.py *.csv *.txt ),那么glob(sys.argv[1]可能不会删除它。您可能需要类似下面的内容。

import sys
from glob import glob

args = [f for l in sys.argv[1:] for f in glob(l)]

This will work even if some arguments dont have wildcard characters in them.即使某些 arguments 中没有通配符,这也会起作用。 ( python abc.txt *.csv anotherfile.dat ) python abc.txt *.csv anotherfile.dat

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM