简体   繁体   English

将命令行参数传递给构造函数

[英]Passing in command line argument to constructor

I am trying to pass in arguments to my constructor in my command line. 我试图在命令行中将参数传递给构造函数。

I am using a text editor and running command line in terminal. 我在终端中使用文本编辑器并运行命令行。

import csv
import sys


class myScraper():


    def __init__(self, fileName=""):
        self.fileName = sys.argv


    def test(self):
        print(self.fileName)



def main():

    obj = myScraper() 
    obj.test()

if __name__=='__main__':
    main()

When I pass in the following into my command line: 当我在命令行中输入以下内容时:

$ python Eithan.py hello

I was expecting for hello to be printed. 我期望打个招呼。

Instead, I get: 相反,我得到:

TypeError: init () missing 1 required positional argument: 'fileName' TypeError: init ()缺少1个必需的位置参数:'fileName'

Why am I missing an argument? 为什么我错过一个论点? I am trying to pass in all arguments through the command line and not in the file. 我试图通过命令行而不是文件中传递所有参数。

If you want to pass in arguments on the command line, you can sys.argv . 如果要在命令行上传递参数,则可以sys.argv However that is not very flexible. 但是,这不是很灵活。 You would be better off using Python's argparse library. 使用Python的argparse库会更好。

Here are a couple of links: 这里有几个链接:

See the code below. 请参见下面的代码。

The right way to do it is to pass the fileName via the main function. 正确的方法是通过main函数传递fileName。 Note that the main will use empty string if the script got no arguments from the caller. 请注意,如果脚本未从调用方获取参数,则main将使用空字符串。

import sys


class myScraper():
    def __init__(self, fileName=""):
        self.fileName = fileName

    def test(self):
        print(self.fileName)


def main(fileName):
    obj = myScraper(fileName)
    obj.test()


if __name__ == '__main__':
    main(sys.argv[1] if len(sys.argv) > 1 else "")

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

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