简体   繁体   English

从Python中的命令行读取Unix通配符文件名

[英]reading Unix wild card filenames from command line in Python

What's the correct way to handle Unix style wildcard arguments using optparse in Python? 在Python中使用optparse处理Unix样式通配符参数的正确方法是什么? I have: 我有:

myscript.py:

from optparse import OptionParser
parser = OptionParser()
parser.add_option("--input", dest="input", default=None, nargs=1)
parser.add_option("--outdir", dest="outdir", default=None, nargs=1)
(options, args) = parser.parse_args()

I want to be able to do: 我希望能够做到:

myscript.py --input *.txt --outdir mydir/

I don't want to necessarily read the contents of all the files matching *.txt . 我不想读取匹配*.txt的所有文件的内容。 I want myscript.py to access their filenames, because some scripts just pass on the filenames to other programs without needing to open/read the files. 我希望myscript.py访问他们的文件名,因为有些脚本只是将文件名传递给其他程序而无需打开/读取文件。 How can I get an iterator that returns the filenames, while still allowing other arguments like --outdir to be passed after the wildcard friendly option (in this case --input )? 如何获得一个返回文件名的迭代器,同时仍允许在通配符友好选项(在本例中为--input )之后传递其他参数,如--outdir thanks. 谢谢。

Unix shells will expand *.txt into separate arguments before they are passed to your program; Unix shell会将*.txt扩展为单独的参数,然后*.txt你的程序; Windows' command interpreter will not. Windows的命令解释器不会。

Assuming you're using an environment where they aren't expanded first -- that is, invoking python prog.py '*.txt' , for instance, you can use glob.glob() to do the expansion yourself. 假设您正在使用一个不首先扩展的环境 - 例如,调用python prog.py '*.txt' ,您可以使用glob.glob()自行进行扩展。

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

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