将参数从cmd传递到python脚本
我用python编写脚本,并通过键入以下命令使用cmd运行脚本:将参数从cmd传递到python脚本,python,cmd,command-line-arguments,Python,Cmd,Command Line Arguments,我用python编写脚本,并通过键入以下命令使用cmd运行脚本: C:\> python script.py 我的一些脚本包含单独的算法和方法,这些算法和方法是基于标志调用的。 现在,我想通过cmd直接传递标志,而不必在运行之前进入脚本并更改标志,我希望类似于: C:\> python script.py -algorithm=2 我曾读到,人们使用sys.argv的目的几乎相同,但在阅读手册和论坛时,我无法理解它是如何工作的。尝试使用getopt模块。它可以处理短命令行和长命令
C:\> python script.py
我的一些脚本包含单独的算法和方法,这些算法和方法是基于标志调用的。
现在,我想通过cmd直接传递标志,而不必在运行之前进入脚本并更改标志,我希望类似于:
C:\> python script.py -algorithm=2
我曾读到,人们使用sys.argv的目的几乎相同,但在阅读手册和论坛时,我无法理解它是如何工作的。尝试使用
getopt
模块。它可以处理短命令行和长命令行选项,并以类似的方式在其他语言(C、shell脚本等)中实现:
请参阅:有几个模块专门用于分析命令行参数:,和
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
这应该让你开始。最糟糕的情况是,网上有大量可用的文档(例如) 它可能无法回答您的问题,但有些人可能会发现它很有用(我在这里寻找): 如何将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])
你检查模块了吗?它的文档非常清晰,应该可以让您开始使用。@PierreGM我以前没有见过这个,这是否意味着我可以添加
parser=argparse.ArgumentParser()
和parser.add_参数(“--Algorithm”)
和args=parser.parse_args()
在我的脚本中,然后在cmd中键入C:\>python script.py--Algorithm=2
,这样算法被设置为2,python脚本将运行与algoritm 2相关的任务?谢谢你的回答,只需几个简单的问题,1.如果u name uuuu==“uu main,的责任是什么__“:
?2.这是一个定义,因此我可以或应该将其保存在一个单独的python脚本中,然后从xxx import*调用我的实际脚本,然后调用如果uuuu name uuuu==“uuu main”:main(sys.argv[1:]
?@Kevin Bell,u name uuuu==”.main的测试”如果脚本是从命令行运行的,而不是从python解释器或其他脚本中导入,则
将返回true。设计取决于您-如果您的程序在单个脚本中是自包含的,那么您只需添加\uuu name\uuu==“\uuuuuuu main\uuuuu”
test以允许从命令行启动脚本。否则,如果导入脚本,则必须将argv参数传递给main()呼叫。我有问题,不知道为什么,但无论如何谢谢。我得到了Pierre GM建议的我想要的东西。如果,比如说,我写了一个语言解释器,我怎么能处理输入文件路径lang file.lang
例如。。。
python "C:\Users\test.pyw" "arg1" "arg2"
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])