Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在一个文件中分别运行多个python方法_Python_Python 3.x - Fatal编程技术网

如何在一个文件中分别运行多个python方法

如何在一个文件中分别运行多个python方法,python,python-3.x,Python,Python 3.x,我有一个文件hello.py,里面有多个方法。我的文件看起来像: def method1(): return data def method2(args): return args if __name__ == '__main__': method1() method2(args) 如果我运行hello.py,所有方法都会运行。但是,例如,如何单独运行这些方法 从你的评论来看,我想你想要的是: def method1(arg): print("hel

我有一个文件
hello.py
,里面有多个方法。我的文件看起来像:

def method1():
    return data

def method2(args):
    return args

if __name__ == '__main__':
    method1()
    method2(args)

如果我运行
hello.py
,所有方法都会运行。但是,例如,如何单独运行这些方法

从你的评论来看,我想你想要的是:

def method1(arg):
    print("hello", arg)

def method2(arg):
    print("Whatsup", arg)

if __name__ == "__main__":
    import sys
    #print(sys.argv)
    func = sys.argv[1]
    arg = sys.argv[2]
    if func == "method1": method1(arg)
    elif func == "method2": method2(arg)
现在通过
python3 hello.py method1 John运行这个

这是一个肮脏的示例,如果您想要更多选项,则需要进行大量调整。

例如,可以从命令行运行
method1

$ python -c 'import hello; hello.method1()'
方法2

$ python -c 'import hello; hello.method2(somearg,someotherarg)'
这要求命令在
hello.py
所在的目录中运行,或者
hello.py
在PYTHONPATH中运行

允许灵活性,您可以根据需要调整字符串并使用任何有效参数运行任何有效方法


有关更多信息,请查看上的答案。

您的意思是您想要一个模块?与hello import method1中的
类似,当运行文件时,会定义函数,但不会执行任何函数。您需要实际调用全局范围内的某个地方的
method1()
。是的,我在
main
下调用这些函数,但我如何才能逐个调用?@JArunMani否一个文件中的所有方法请看一看?然后像往常一样单独调用它们。