我用python编写脚本,并通过键入以下内容使用cmd运行它们:
C:\> python script.py
我的一些脚本包含独立的算法和方法,这些算法和方法是基于标志调用的。现在我想直接通过cmd传递标志,而不是在运行之前进入脚本并更改标志,我想要类似于:
C:\> python script.py -algorithm=2
我读到过人们将sys.argv用于几乎类似的目的,但是在阅读手册和论坛时,我无法理解它是如何工作的。
发布于 2013-05-23 12:30:10
有一些专门用于解析命令行参数的模块:getopt
、optparse
和argparse
。optparse
已被弃用,而且getopt
的功能不如argparse
,所以我建议您使用后者,从长远来看,它会更有帮助。
下面是一个简短的示例:
import argparse
# Define the parser
parser = argparse.ArgumentParser(description='Short sample app')
# Declare an argument (`--algo`), saying that the
# corresponding value should be stored in the `algo`
# field, and using a default value if the argument
# isn't given
parser.add_argument('--algo', action="store", dest='algo', default=0)
# Now, parse the command line arguments and store the
# values in the `args` variable
args = parser.parse_args()
# Individual arguments can be accessed as attributes...
print args.algo
这应该会让你开始学习。在最坏的情况下,在线上有很多文档可用(例如,this one )……
发布于 2019-05-01 05:33:01
它可能不会回答你的问题,但有些人可能会发现它很有用(我在这里寻找这个):
如何从cmd向python 3发送2个参数(arg1 + arg2):
-在test.cmd中发送参数:
python "C:\Users\test.pyw" "arg1" "arg2"
-检索test.py中的参数:
print ("This is the name of the script= ", sys.argv[0])
print("Number of arguments= ", len(sys.argv))
print("all args= ", str(sys.argv))
print("arg1= ", sys.argv[1])
print("arg2= ", sys.argv[2])
发布于 2013-05-23 11:40:38
尝试使用getopt
模块。它既可以处理短命令行选项,也可以处理长命令行选项,并以类似的方式在其他语言(C、shell脚本等)中实现:
import sys, getopt
def main(argv):
# default algorithm:
algorithm = 1
# parse command line options:
try:
opts, args = getopt.getopt(argv,"a:",["algorithm="])
except getopt.GetoptError:
<print usage>
sys.exit(2)
for opt, arg in opts:
if opt in ("-a", "--algorithm"):
# use alternative algorithm:
algorithm = arg
print "Using algorithm: ", algorithm
# Positional command line arguments (i.e. non optional ones) are
# still available via 'args':
print "Positional args: ", args
if __name__ == "__main__":
main(sys.argv[1:])
然后,可以通过使用-a
或--algorithm=
选项指定不同的算法:
python <scriptname> -a2 # use algorithm 2
python <scriptname> --algorithm=2 # ditto
https://stackoverflow.com/questions/16712795
复制