Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Python class methods from the command line

so I wrote some class in a Python script like:

#!/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 am I able to call method? so usually I enter: $ python test.py test_file Now I just need to know how to access the class function called "method".

like image 498
JadenBlaine Avatar asked Jul 13 '15 09:07

JadenBlaine


People also ask

How do you call a class method in Python?

To call a class method, put the class as the first argument. Class methods can be can be called from instances and from the class itself. All of these use the same method. The method can use the classes variables and methods.

How do I run a Python class from the command line?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!

How do you call a method in Python?

Once a function is created in Python, we can call it by writing function_name() itself or another function/ nested function. Following is the syntax for calling a function. Syntax: def function_name():

How do you call a Python shell from the command line?

To run the Python Shell, open the command prompt or power shell on Windows and terminal window on mac, write python and press enter. A Python Prompt comprising of three greater-than symbols >>> appears, as shown below. Now, you can enter a single statement and get the result.


1 Answers

You'd create an instance of the class, then call the method:

test_instance = test(filepath)
test_instance.method()

Note that in Python you don't have to create classes just to run code. You could just use a 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 a __main__ guard so that you can also use the script as a module and import the read_csv() function for use elsewhere.

like image 147
Martijn Pieters Avatar answered Sep 28 '22 23:09

Martijn Pieters