【问题标题】:Call Python class methods from the command line从命令行调用 Python 类方法
【发布时间】:2015-10-01 12:56:18
【问题描述】:

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

#!/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 现在我只需要知道如何访问名为“方法”的类函数。

【问题讨论】:

标签: python class methods sys


【解决方案1】:

您将创建该类的一个实例,然后调用该方法:

test_instance = test(filepath)
test_instance.method()

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

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() 函数以在其他地方使用。

【讨论】:

  • 我知道我可以使用该函数而无需在类中编写它,但我只是好奇如何做到这一点:)
【解决方案2】:

从命令行打开 Python 解释器。

$ python

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    • 2016-11-07
    相关资源
    最近更新 更多