【问题标题】:How do I call a specific python function in a file from the command line? [duplicate]如何从命令行调用文件中的特定 python 函数? [复制]
【发布时间】:2018-01-23 16:57:26
【问题描述】:

假设在名为 fb_auth_token.py 的文件中有以下函数

def get_fb_access_token(email, password):
...
return ...

如何从 bash 运行它? python fb_auth_token.py get_fb_access?。如何只调用一个特定的函数?

【问题讨论】:

  • 这取决于你到底想做什么。例如,您可以在 Python 文件中调用它:print(get_fb_access_token(email, password))。然后运行python fb_auth_token.py

标签: python


【解决方案1】:

您可以使用命令选项调用 python:

python -c "from file_name import function;function()"

或者如果您希望每次执行脚本时都调用此函数,您可以添加该行

if __name__ == "__main__":
    function()

只有当文件被直接执行时才会执行这个函数(即你仍然可以将它导入另一个脚本而不调用“函数”)。

【讨论】:

    【解决方案2】:

    您可以使用-c 命令行参数。例如:

    python -c 'import fb_auth_token; fb_auth_token.get_fb_access_token("email", "password")'
    

    【讨论】:

      【解决方案3】:

      我想通了:

      python -c 'import fb_auth_token; print fb_auth_token.get_fb_access_token("email", "password")'

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-15
        • 2015-01-12
        • 1970-01-01
        • 1970-01-01
        • 2014-06-11
        • 1970-01-01
        • 1970-01-01
        • 2017-01-08
        相关资源
        最近更新 更多