简体   繁体   English

Python sys.argv和argparse

[英]Python sys.argv and argparse

I have been looking for ways to add argument values to a script when I run it from the command line. 我一直在寻找从命令行运行它时为脚本添加参数值的方法。 The two packages I have found that seem to do this are sys.argv and argparse. 我发现似乎这样做的两个包是sys.argv和argparse。

I'd also like to be able to add some sort of help function if possible. 如果可能的话,我也希望能够添加某种帮助功能。

Can somebody explain the difference between the two, and perhaps what would be easier for someone starting out? 有人可以解释两者之间的区别,或许对于一个人开始会更容易吗?

sys.argv is simply a list of the commandline arguments. sys.argv只是命令行参数的列表。

argparse is a full featured commandline parser which generally parses sys.argv and gives you back the data in a much easier to use fashion. argparse是一个功能齐全的命令行解析器,它通常解析 sys.argv并以更容易使用的方式返回数据。

If you're doing anything more complicated than a script that accepts a few required positional arguments, you'll want to use a parser. 如果您正在做一些比接受一些必需位置参数的脚本更复杂的事情,那么您将需要使用解析器。 Depending on your python version, there are 3 available in the python standard library ( getopt , optparse and argparse ) and argparse is by far the best. 根据您的python版本,python标准库中有3个可用( getoptoptparseargparse ), argparse是目前最好的。

I would recommend you use argparse for your command line arguments for two reasons. 我建议您使用argparse作为命令行参数,原因有两个。 Making an arg is very straight forward as pointed out in the documentation, and second because you want a help function argparse gives you it for free. 如文档中所指出的,制作arg非常简单,其次因为你想要一个帮助函数argparse免费提供它。

Documentation: https://docs.python.org/2/howto/argparse.html 文档: https//docs.python.org/2/howto/argparse.html

Let me know if you need more help. 如果您需要更多帮助,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM