如何在一个文件中分别运行多个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否一个文件中的所有方法请看一看?然后像往常一样单独调用它们。