简体   繁体   English

从命令行传递值 python

[英]Passing values from command line python

I have a python function that requires several parameters.我有一个 python function 需要几个参数。 Something like:就像是:

def func(par1=1, par2=2, par3=3):
... 

I want to make this callable from command line such as: function.py par1=1 par2=2 par3=3 .我想让它可以从命令行调用,例如: function.py par1=1 par2=2 par3=3

I was thinking of doing it something like this:我正在考虑这样做:

import sys

if sys.argv[0][0:4]=="par1":
   par1=int(sys.argv[0][5:])
else:
   par1=1

but it doesn't look very nice, as the user might pass just some parametrs, or they might pass it as par1 =1 or par1= 1 or par1 = 1 so I would have to hard code with if-else all these possibilities.但它看起来不太好,因为用户可能只传递一些参数,或者他们可能将其作为par1 =1par1= 1par1 = 1传递,所以我将不得不用 if-else 硬编码所有这些可能性。 Is there a nicer, more professional solution?有更好、更专业的解决方案吗? Thank you!谢谢!

Use argparse from the standard library使用标准库中的argparse

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--par1", type=int, default=1, help="This is the description")
opts = parser.parse_args()

print(opts.part1)

checkout the docs for more details: https://docs.python.org/3/library/argparse.html查看文档以获取更多详细信息: https://docs.python.org/3/library/argparse.html

As mentioned in Amadan's comment, you probably want function.py --par1=1 --par2=2 --par3=3 and not function.py par1=1 par2=2 par3=3正如 Amadan 的评论中提到的,您可能需要function.py --par1=1 --par2=2 --par3=3而不是function.py par1=1 par2=2 par3=3

For the former, you can use对于前者,您可以使用

function.py function.py

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--par1", default=11)
parser.add_argument("--par2", default=22)
parser.add_argument("--par3", default=33)
parser.add_argument("--par4", default=44)
opts = parser.parse_args()

print(opts.par1, opts.par2, opts.par3, opts.par4)
$ python function.py  # default values
11 22 33 44

$ python function.py --par1 99  # spaces are OK
99 22 33 44

$ python function.py --par1=99  # = are OK
99 22 33 44

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

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