这是一个简单的教程,涉及argpase。
但首先,如果您想在使用argparse模块时拥有更多控制权,我建议您阅读official documentation。
此外,如果你想传递参数到Spyder,我会建议@Carlos Cordoba谁回答建议看到这个answer。
我的教程脚本:
import argparse
class CommandLine:
def __init__(self):
parser = argparse.ArgumentParser(description = "Description for my parser")
parser.add_argument("-H", "--Help", help = "Example: Help argument", required = False, default = "")
parser.add_argument("-s", "--save", help = "Example: Save argument", required = False, default = "")
parser.add_argument("-p", "--print", help = "Example: Print argument", required = False, default = "")
parser.add_argument("-o", "--output", help = "Example: Output argument", required = False, default = "")
argument = parser.parse_args()
status = False
if argument.Help:
print("You have used '-H' or '--Help' with argument: {0}".format(argument.Help))
status = True
if argument.save:
print("You have used '-s' or '--save' with argument: {0}".format(argument.save))
status = True
if argument.print:
print("You have used '-p' or '--print' with argument: {0}".format(argument.print))
status = True
if argument.output:
print("You have used '-o' or '--output' with argument: {0}".format(argument.output))
status = True
if not status:
print("Maybe you want to use -H or -s or -p or -p as arguments ?")
if __name__ == '__main__':
app = CommandLine()
现在,在你的终端或Spyder:
$ python3 my_script.py -H Help -s Save -p Print -o Output
输出:
You have used '-H' or '--Help' with argument: Help
You have used '-s' or '--save' with argument: Save
You have used '-p' or '--print' with argument: Print
You have used '-o' or '--output' with argument: Output
而当你使用-h
或--help
作为参数你将有这个输出:
$ python3 my_script.py -h
输出:
usage: my_script.py [-h] [-H HELP] [-s SAVE] [-p PRINT] [-o OUTPUT]
Description for my parser
optional arguments:
-h, --help show this help message and exit
-H HELP, --Help HELP Example: Help argument
-s SAVE, --save SAVE Example: Save argument
-p PRINT, --print PRINT
Example: Print argument
-o OUTPUT, --output OUTPUT
Example: Output argument
您应该使用命令行参数解析的[argparse](https://docs.python.org/2.7/library/argparse.html)模块。 – skrrgwasme
要将命令行参数传递给Spyder,请参阅:http://stackoverflow.com/questions/26679272/not-sure-how-to-use-argv-with-spyder –