Call Python class methods from the command line
Asked Answered
H

2

8

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

Hereafter answered 13/7, 2015 at 9:58 Comment(2)
be a little more clearSelsyn
possible duplicate of Python: Run function from the command lineAnnabelleannabergite
M
4

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.

Mcclees answered 13/7, 2015 at 10:0 Comment(1)
I know that I could use the function without writing it inside a class but I was simply curious about how it would be possible to do this:)Hereafter
S
3

Open Python interpreter from the command line.

$ python

Import your python code module, make a class instance and call the method.

>>> import test
>>> instance = test(test_file)
>>> instance.method()
Sharonsharona answered 25/1, 2017 at 18:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.