将参数从命令行传递给Python脚本

9 浏览
0 Comments

将参数从命令行传递给Python脚本

这个问题已经有答案了

如何读取/处理命令行参数?

我用python编写我的脚本,并通过在cmd中输入以下命令来运行它们:

C:\> python script.py

我的一些脚本包含单独的算法和方法,这些算法和方法是基于标志调用的。现在,我希望直接通过cmd传递标志,而不是在运行前进入脚本并更改标志,我想要类似于:

C:\> python script.py -algorithm=2

我已经阅读了使用sys.argv来处理类似用途的资料,但是阅读手册和论坛时我无法理解它的工作原理。

admin 更改状态以发布 2023年5月24日
0
0 Comments

它可能不能回答你的问题,但某些人可能会发现它有用(我在这里正在寻找这个):

如何将2个参数(arg1 + arg2)从cmd发送到python 3:

----- 在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])

0
0 Comments

有一些专门用于解析命令行参数的模块:getoptoptparseargparseoptparse已经过时,而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

这样应该可以让您开始了。最坏的情况是,有丰富的文档在线可用(例如,这个)...

0