从命令行调用 Python 类方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31380347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:53:40  来源:igfitidea点击:

Call Python class methods from the command line

pythonclassmethodssys

提问by JadenBlaine

so I wrote some class in a Python script like:

所以我在 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]

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

如果我从命令行调用这个脚本,我怎样才能调用方法?所以通常我输入: $ python test.py test_file 现在我只需要知道如何访问名为“method”的类函数。

采纳答案by Martijn Pieters

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 haveto create classes just to run code. You could just use a simple function here:

请注意,在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])

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

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

回答by Ishu Goyal

Open Python interpreter from the command line.

从命令行打开 Python 解释器。

$ python

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

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

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