从命令行调用 Python class 方法

Call Python class methods from the command line

所以我在 Python 脚本中写了一些 class,例如:

#!/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]

如果我从命令行调用这个脚本,我如何调用方法? 所以通常我输入:$ python test.py test_file 现在我只需要知道如何访问名为 "method".

的 class 函数

您将创建 class 的实例,然后调用方法:

test_instance = test(filepath)
test_instance.method()

请注意,在 Python 中,您 没有 来为 运行 代码创建 classes。你可以在这里使用一个简单的函数:

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

我将函数调用移至 __main__ 守卫,以便您可以 将脚本用作模块并导入 read_csv() 函数在其他地方使用。

从命令行打开 Python 解释器。

$ python

导入您的 python 代码模块,创建一个 class 实例并调用该方法。

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