在Python中将argparse与sys.argv结合使用

时间:2023-02-01 23:16:23

I currently have a script, which uses file globbing via the sys.argv variable like this:

我目前有一个脚本,它通过sys.argv变量使用文件globbing,如下所示:

if len(sys.argv) > 1:
        for filename in sys.argv[1:]:

This works great for processing a bunch of files; however, I would like to use this with the argparse module as well. So, I would like my program to be able to handle something like the following:

这非常适合处理一堆文件;但是,我想将它与argparse模块一起使用。所以,我希望我的程序能够处理如下内容:

foo@bar:~$ myScript.py --filter=xyz *.avi

Has anyone tried to do this, or have some pointers on how to proceed?

有没有人试图这样做,或者有一些关于如何进行的指示?

2 个解决方案

#1


15  

If I got you correctly, your question is about passing a list of files together with a few flag or optional parameters to the command. If I got you right, then you just must leverage the argument settings in argparse:

如果我找到了你,你的问题是将一个文件列表与一些标志或可选参数一起传递给命令。如果我找对你,那么你只需要利用argparse中的参数设置:

File p.py

import argparse

parser = argparse.ArgumentParser(description='SO test.')
parser.add_argument('--doh', action='store_true')
parser.add_argument('files', nargs='*')  # This is it!!
args = parser.parse_args()
print(args.doh)
print(args.files)

The commented line above inform the parser to expect an undefined number >= 0 (nargs ='*') of positional arguments.

上面的注释行通知解析器期望位置参数的未定义数字> = 0(nargs ='*')。

Running the script from the command line gives these outputs:

从命令行运行脚本会提供以下输出:

$ ./p.py --doh *.py
True
['p2.py', 'p.py']
$ ./p.py *.py
False
['p2.py', 'p.py']
$ ./p.py p.py
False
['p.py']
$ ./p.py 
False
[]

Observe how the files will be in a list regardless of them being several or just one.

观察文件在列表中的位置,无论它们是多少还是只有一个。

HTH!

#2


1  

Alternatively you may use both in the following way:

或者,您可以通过以下方式使用两者:

import sys
import argparse
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("-v", "--verbose", help="increase verbosity", action="store_true")
    args, unknown = parser.parse_known_args()
    for file in sys.argv:
        if not file.startswith("-"):
            print(file)

However this will work only for standalone parameters, otherwise the argument values would be treated as file arguments (unless you'll not separate them with space or you'll improve the code further more).

但是,这仅适用于独立参数,否则参数值将被视为文件参数(除非您不将它们与空格分开,否则您将进一步改进代码)。

#1


15  

If I got you correctly, your question is about passing a list of files together with a few flag or optional parameters to the command. If I got you right, then you just must leverage the argument settings in argparse:

如果我找到了你,你的问题是将一个文件列表与一些标志或可选参数一起传递给命令。如果我找对你,那么你只需要利用argparse中的参数设置:

File p.py

import argparse

parser = argparse.ArgumentParser(description='SO test.')
parser.add_argument('--doh', action='store_true')
parser.add_argument('files', nargs='*')  # This is it!!
args = parser.parse_args()
print(args.doh)
print(args.files)

The commented line above inform the parser to expect an undefined number >= 0 (nargs ='*') of positional arguments.

上面的注释行通知解析器期望位置参数的未定义数字> = 0(nargs ='*')。

Running the script from the command line gives these outputs:

从命令行运行脚本会提供以下输出:

$ ./p.py --doh *.py
True
['p2.py', 'p.py']
$ ./p.py *.py
False
['p2.py', 'p.py']
$ ./p.py p.py
False
['p.py']
$ ./p.py 
False
[]

Observe how the files will be in a list regardless of them being several or just one.

观察文件在列表中的位置,无论它们是多少还是只有一个。

HTH!

#2


1  

Alternatively you may use both in the following way:

或者,您可以通过以下方式使用两者:

import sys
import argparse
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("-v", "--verbose", help="increase verbosity", action="store_true")
    args, unknown = parser.parse_known_args()
    for file in sys.argv:
        if not file.startswith("-"):
            print(file)

However this will work only for standalone parameters, otherwise the argument values would be treated as file arguments (unless you'll not separate them with space or you'll improve the code further more).

但是,这仅适用于独立参数,否则参数值将被视为文件参数(除非您不将它们与空格分开,否则您将进一步改进代码)。