简体   繁体   English

如何将argparse参数传递给类

[英]how to pass argparse arguments to a class

I'm very new to coding in general and Python in particular. 我对一般的代码特别是Python还是很陌生的。 I'm trying to learn how to pass argparse arguments I have created into a class for use the right/recommend way. 我正在尝试学习如何将我创建的argparse参数传递到类中,以使用正确/推荐的方式。 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外,我还尝试学习如何以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 inside the class. 因此,我要在主类之外定义argparse参数,并想知道如何将其放入类中。 Is this even the right way to do it? 这是正确的方法吗? should I just make argparse a function under my class? 我应该只让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. RyPeck的答案帮助我获取了参数(缺少我的代码),但是随后,当我尝试测试代码时,我遇到了未绑定的方法错误。 I had no idea what that meant. 我不知道那是什么意思。 Did I mention that I live up to my screen name? 我是否提到我不辜负自己的屏幕名称?

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. 不带任何参数运行此代码将打印False四次。 two times outside of the class instance, two times within the class instance. 在类实例之外两次,在类实例内部两次。

Use parser.parse_args and wrap it with vars to convert the special argparse Namespace type to a regular Python dict. 使用parser.parse_args并将其与vars一起包装,以将特殊的argparse命名空间类型转换为常规Python dict。 In general, you want this pattern: 通常,您需要以下模式:

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 c1 and c2 will be created. 将同时创建c1c2 Best approach, though, is to create classes explicitly, as is done with c1 . 不过,最好的方法是像c1一样显式地创建类。

A simple for loop 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 argparse and 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

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 documentation for greater detail and more info. 有关更多详细信息和更多信息,请参见argparse文档

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

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