Call Python class methods from the command line

so I wrote some class in a Python script, for example:

#!/usr/bin/python import sys import csv filepath = sys.argv[1] class test(object): def __init__(self, filepath): self.filepath = filepath def method(self): list = [] with open(self.filepath, "r") as table: reader = csv.reader(table, delimiter="\t") for line in reader: list.append[line] 

If I call this script from the command line, how can I call the method? so usually I go in: $ python test.py test_file Now I just need to know how to access the class function called the "method".

+6
source share
3 answers

You must create an instance of the class and then call the method:

 test_instance = test(filepath) test_instance.method() 

Note that in Python you do not need to create classes just to run the code. You can simply use the simple function here:

 import sys import csv def read_csv(filepath): list = [] with open(self.filepath, "r") as table: reader = csv.reader(table, delimiter="\t") for line in reader: list.append[line] if __name__ == '__main__': read_csv(sys.argv[1]) 

where I moved the function call to __main__ guard so that you can also use the script as a module and import the read_csv() function for use elsewhere.

+2
source

Open the Python interpreter from the command line.

 $ python 

Import the python code module, instantiate the class, and call the method.

 >>> import test >>> instance = test(test_file) >>> instance.method() 
0
source

On the command line, I imported all the classes from the blockchain package. But when I tried to create its “instance”, for example, “b = Blockchain ()”, I get the error message “Blockchain name is not defined”. However, I am using python_2_7_14. What is the solution?

0
source

All Articles