社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

Nerd • 6 年前 • 1768 次点击  

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

def method1():
    return data

def method2(args):
    return args

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

你好,py ,所有方法都运行。但是,例如,如何分别运行这些方法?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/53224
文章 [ 2 ]  |  最新文章 6 年前
J Arun Mani
Reply   •   1 楼
J Arun Mani    6 年前

所以从你的评论来看,我认为你希望:

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 这是一个肮脏的例子,如果你想要更多的选择,你需要调整很多。

Attersson
Reply   •   2 楼
Attersson    6 年前

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

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

或 method2 :

$ python -c 'import hello; hello.method2(somearg,someotherarg)'

这需要在以下目录中运行命令 hello.py 是,或 在蟒蛇城。

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

有关详细信息,请查看 how to run functions from the command line