使用一些可选参数运行python脚本 [英] Run python script with some of the argument that are optional
问题描述
我已经阅读过sys
文档,但是我仍然不清楚.我一直在寻找关于stackoverflow的类似问题,但是我没有发现任何有用的东西(显然,任何参考文献都值得赞赏!).
I have gone through the sys
documentation, however there is something that is still unclear to me. I have looked for some similar question on stackoverflow, but I haven't find anything useful (clearly any reference is appreciated!).
我想创建一个脚本-例如foo.py
-我想在其中从3到6个参数传递
I want to create a script - say foo.py
- in which I want pass from 3 to 6 arguments:
$ python foo.py arg1 arg2 arg3
在任何情况下都必须给出前三个参数;如果未传递任何内容,则在具有默认参数值的函数中使用最后3个参数.
The first 3 arguments must be given in any case; the last 3 arguments are used in a function that have default argument values if nothing is passed.
问题是我该怎么做?到目前为止,我一直在考虑编写类似于以下foo.py
的内容(这是一个简单的示例,仅出于提供具体支持我的问题的目的而设置):
The question is how do I do this? So far I was thinking to write something like the following foo.py
(this is an easy example set only for the purpose of having something concrete in support of my question):
import sys
def example(credit_mom, credit_dad, debt_mom, debt_dad = 1000,
salary = 2000, bonus = 0):
total_gain = salary + credit_dad + credit_mom + bonus
total_loss = debt_dad + debt_mom
return total_gain - total_loss
if __name__ == '__main__':
if len(sys.argv) < 4:
sys.exit('Need at least 3 arguments. The order is as follows:\n\
1.credit_mom;\n\
2.credit_dad;\n\
3.debt_mom;\n\
4.others')
else:
sys.exit(example(sys.argv[1],
sys.argv[2],
sys.argv[3],
sys.argv[4],
sys.argv[5],
sys.argv[6]))
如果我运行此脚本,很明显会出现IndexError
异常:
If I run this script I clearly get an IndexError
exception:
$ python foo.py 110 110 220
Traceback (most recent call last):
File "foo.py", line 19, in <module>
sys.argv[4],
IndexError: list index out of range
推荐答案
使用Argparse
我建议您使用 argparse (和字符串(如果提供).
Using Argparse
I suggest you use argparse (and here is the tutorial ). Saves you having to manually check for the existence of parameters. Moreover argparse gives you the --help
argument as a freebie, which will read the help=""
string defined for each argument, if provided.
在您的情况下,您具有三个强制(位置)参数和三个可选参数.样本argparse代码如下所示:
In your case you have three mandatory (positional) argument and three optional ones. A sample argparse code would look like this:
#!/usr/bin/python
# coding: utf-8
import argparse
def parseArguments():
# Create argument parser
parser = argparse.ArgumentParser()
# Positional mandatory arguments
parser.add_argument("creditMom", help="Credit mom.", type=float)
parser.add_argument("creditDad", help="Credit dad.", type=float)
parser.add_argument("debtMom", help="Debt mom.", type=float)
# Optional arguments
parser.add_argument("-dD", "--debtDad", help="Debt dad.", type=float, default=1000.)
parser.add_argument("-s", "--salary", help="Debt dad.", type=float, default=2000.)
parser.add_argument("-b", "--bonus", help="Debt dad.", type=float, default=0.)
# Print version
parser.add_argument("--version", action="version", version='%(prog)s - Version 1.0')
# Parse arguments
args = parser.parse_args()
return args
def example(credit_mom, credit_dad, debt_mom, debt_dad = 1000, salary = 2000, bonus = 0):
total_gain = salary + credit_dad + credit_mom + bonus
total_loss = debt_dad + debt_mom
return total_gain - total_loss
if __name__ == '__main__':
# Parse the arguments
args = parseArguments()
# Raw print arguments
print("You are running the script with arguments: ")
for a in args.__dict__:
print(str(a) + ": " + str(args.__dict__[a]))
# Run function
print(example(args.creditMom, args.creditDad, args.debtMom, args.debtDad, args.salary, args.bonus))
这篇关于使用一些可选参数运行python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!