Python 如何将 argparse 参数传递给类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20021693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to pass argparse arguments to a class
提问by some_noob
I'm very new to coding in general and Python in particular. I'm trying to learn how to pass argparse arguments I have created into a class for use the right/recommend way. In addition to learning python, I'm trying to learn how to do things in an OOP manner so that learning other, OOP-type languages comes a bit easier.
我对一般的编码特别是 Python 很陌生。我正在尝试学习如何将我创建的 argparse 参数传递到类中以使用正确/推荐的方式。除了学习 Python 之外,我还试图学习如何以 OOP 方式做事,以便学习其他 OOP 类型的语言变得更容易一些。
So here's a sample of what I am trying to do:
所以这是我正在尝试做的一个示例:
import argparse
class passyourcliargstome():
def __init__(self, whatdoiputheretogetmycliargs):
#how do I get my cli args here?
pass
def otherfunctionsthatdothings():
pass
if __name__ == '__main__':
#grab the arguments when the script is ran
parser = argparse.ArgumentParser(
description='Make things happen.')
parser.add_argument('-f', '--foo', action='store_true', default=False, help='here be dragons')
parser.add_argument('-b', '--bar', action='store_true', default=False, help='here be more dragons')
passyourcliargstome.otherfunctionsthatdothings()
So, I'm defining argparse arguments outside of the main class, and want to know how to get them insidethe class. Is this even the right way to do it? should I just make argparse a function under my class?
所以,我在主类之外定义了 argparse 参数,并想知道如何将它们放入类中。这甚至是正确的方法吗?我应该在我的班级下让 argparse 成为一个函数吗?
Thank you in advance for any assistance, references, etc.
在此先感谢您提供任何帮助、参考资料等。
Edit: 11/16 2:18 EST
编辑:11/16 2:18 EST
Note: Since I don't have enough rep to answer my own question, this is my only recourse for posting a proper answer.
注意:由于我没有足够的代表来回答我自己的问题,这是我发布正确答案的唯一途径。
Okay, it took me some doing, but I managed to piece this together. RyPeck's answers helped me in getting my arguments (something my code was missing), but then afterwards I was getting unbound method errors When I was trying to test the code. I had no idea what that meant. Did I mention that I live up to my screen name?
好吧,我花了一些时间,但我设法把它拼凑起来。RyPeck 的答案帮助我获得了我的论点(我的代码丢失了一些东西),但后来我在尝试测试代码时遇到了未绑定的方法错误。我不知道那是什么意思。我有没有提到我辜负了我的网名?
It didn't really click until I found and read this. Here is my working code. If anyone has anything to add to this, up to and including "You're still doing it wrong, do it this way, the right way." I'm all ears. In the meantime, thanks for your help.
它并没有真正点击,直到我发现读这个。这是我的工作代码。如果有人对此有任何补充,包括“您仍然做错了,以正确的方式这样做”。我都是耳朵。同时,感谢您的帮助。
import argparse
class Passyourcliargstome(object):
def __init__(self):
#here's how I got my args here
self.foo = args.foo
self.bar = args.bar
def otherfunctionsthatdothings(self):
print "args inside of the main class:"
print self.foo
print self.bar
if __name__ == '__main__':
#grab the arguments when the script is ran
parser = argparse.ArgumentParser(description='Make things happen.')
parser.add_argument('-f', '--foo', action='store_true', default=False, help='here be dragons')
parser.add_argument('-b', '--bar', action='store_true', default=False, help='here be more dragons')
args = parser.parse_args()
print "args outside of main:"
print args.foo
print args.bar
#this was the part that I wasn't doing, creating an instance of my class.
shell = Passyourcliargstome()
shell.otherfunctionsthatdothings()
Running this code with no arguments prints False four times. two times outside of the class instance, two times within the class instance.
不带参数运行此代码会打印四次 False。两次在类实例之外,两次在类实例内。
回答by RyPeck
You have to do the following after you add your arguments.
添加参数后,您必须执行以下操作。
args = parser.parse_args()
If you do a print on args, you'll see that you have all the arguments in a namespace argument.
如果您对 args 进行打印,您将看到名称空间参数中包含所有参数。
You can then access them like so -
然后你可以像这样访问它们 -
print args.foo
print args.bar
From there, you can treat them like normal variables. See the argparse documentationfor greater detail and more info.
从那里,您可以将它们视为普通变量。有关更多详细信息和更多信息,请参阅argparse 文档。
回答by Assaf-g
A simple forloop can pass argument (or- set your attributes):
一个简单的for循环可以传递参数(或设置您的属性):
args_dict = vars(self.parser.parse_args())
# using argparse arguments as attributes of this (self) class
for item in args_dict:
setattr(self, item, args_dict[item])
but... maybe the elegant way would be to initialize your class with argparseand set them directly to the class by namespace:
但是......也许优雅的方法是初始化你的类argparse并通过命名空间将它们直接设置为类:
class Foo:
def __init__(self)
self.parser = ArgumentParser()
self.parser.add_argument('-f', '--foo, default=False, action='store_true', help='foo or not?')
self.parser.add_argument('-b', '--bar', default=0, action='store', help='set the bar')
self.parser.parse_args(namespace=self)
an empty input is equivalent to:
空输入相当于:
class Foo:
def __init__(self)
self.foo = False
self.bar = 0
回答by Dave
Use parser.parse_argsand wrap it with varsto convert the special argparse Namespacetype to a regular Python dict. In general, you want this pattern:
使用parser.parse_args并包装它vars以将特殊的 argparse 命名空间类型转换为常规 Python dict。通常,您需要这种模式:
def main():
parser = argparse.ArgumentParser()
parser.add_argument('foo')
parser.add_argument('bar')
args = parser.parse_args()
args_dict = vars(args)
After that, you can pass arguments explicitly or all at once to whatever class or function will take it. For a class, it is best to write the required arguments explicitly. Like so:
之后,您可以将参数显式或一次性传递给任何类或函数。对于类,最好明确编写所需的参数。像这样:
class MyClass(object):
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
def Print(self):
print self.foo
print self.bar
Now you can put those two together like this:
现在你可以像这样把这两个放在一起:
import argparse
class MyClass(object):
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
def Print(self):
print self.foo
print self.bar
def main():
parser = argparse.ArgumentParser()
parser.add_argument('foo')
parser.add_argument('bar')
args = parser.parse_args()
c1 = MyClass(args.foo, args.bar)
args_dict = vars(args)
c2 = MyClass(**args_dict)
Both c1and c2will be created. Best approach, though, is to create classes explicitly, as is done with c1.
双方c1并c2会被创建。不过,最好的方法是显式创建类,就像使用c1.

