简体   繁体   中英

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'

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 . However that is not very flexible. You would be better off using Python's argparse library.

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. Note that the main will use empty string if the script got no arguments from the caller.

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 "")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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