我有这样的代码:

def hello():
    return 'Hi :)'

我如何直接从命令行运行它?


当前回答

使用-c(命令)参数(假设你的文件名为foo.py):

$ python -c 'import foo; print foo.hello()'

或者,如果你不关心命名空间污染:

$ python -c 'from foo import *; print hello()'

中间立场是:

$ python -c 'from foo import hello; print hello()'

其他回答

从myfile导入hello;hello() `,其中myfile必须替换为Python脚本的基名。(例如,myfile.py变成myfile)。

但是,如果hello()是Python脚本中的“永久”主入口点,那么通常的方法如下:

def hello():
    print "Hi :)"

if __name__ == "__main__":
    hello()

这允许您通过运行python myfile.py或python -m myfile来执行脚本。

这里解释一下:__name__是一个特殊的Python变量,保存当前正在执行的模块的名称,除非从命令行启动模块,在这种情况下,它会变成"__main__"。

只要把hello()放在函数下面的某个地方,它就会在你执行python your_file.py时执行

为了一个更简洁的解决方案,你可以使用这个:

if __name__ == '__main__':
    hello()

这样,函数只会在运行文件时执行,而不会在导入文件时执行。

这个脚本类似于这里的其他答案,但它也列出了可用的函数,带有参数和文档字符串:

"""Small script to allow functions to be called from the command line.
Run this script without argument to list the available functions:

    $ python many_functions.py
    Available functions in many_functions.py:

    python many_functions.py a  : Do some stuff

    python many_functions.py b  : Do another stuff

    python many_functions.py c x y : Calculate x + y

    python many_functions.py d  : ?

Run this script with arguments to try to call the corresponding function:

    $ python many_functions.py a
    Function a

    $ python many_functions.py c 3 5
    3 + 5 = 8

    $ python many_functions.py z
    Function z not found
"""

import sys
import inspect

#######################################################################
#                         Your functions here                         #
#######################################################################

def a():
    """Do some stuff"""
    print("Function a")

def b():
    """Do another stuff"""
    a()
    print("Function b")

def c(x, y):
    """Calculate x + y"""
    print(f"{x} + {y} = {int(x) + int(y)}")

def d():
    # No doc
    print("Function d")

#######################################################################
#         Some logic to find and display available functions          #
#######################################################################

def _get_local_functions():
    local_functions = {}
    for name, obj in inspect.getmembers(sys.modules[__name__]):
        if inspect.isfunction(obj) and not name.startswith('_') and obj.__module__ == __name__:
            local_functions[name] = obj
    return local_functions

def _list_functions(script_name):
    print(f"Available functions in {script_name}:")
    for name, f in _get_local_functions().items():
        print()
        arguments = inspect.signature(f).parameters
        print(f"python {script_name} {name} {' '.join(arguments)} : {f.__doc__ or '?'}")


if __name__ == '__main__':
    script_name, *args = sys.argv
    if args:
        functions = _get_local_functions()
        function_name = args.pop(0)
        if function_name in functions:
            function = functions[function_name]
            function(*args)
        else:
            print(f"Function {function_name} not found")
            _list_functions(script_name)
    else:
        _list_functions(script_name)

运行不带参数的脚本列出可用的函数:

$ python many_functions.py
Available functions in many_functions.py:

python many_functions.py a  : Do some stuff

python many_functions.py b  : Do another stuff

python many_functions.py c x y : Calculate x + y

python many_functions.py d  : ?

运行这个带有参数的脚本,尝试调用相应的函数:

$ python many_functions.py a
Function a

$ python many_functions.py c 3 5
3 + 5 = 8

$ python many_functions.py z
Function z not found

使用-c(命令)参数(假设你的文件名为foo.py):

$ python -c 'import foo; print foo.hello()'

或者,如果你不关心命名空间污染:

$ python -c 'from foo import *; print hello()'

中间立场是:

$ python -c 'from foo import hello; print hello()'

就像这样: call_from_terminal.py

# call_from_terminal.py
# Ex to run from terminal
# ip='"hi"'
# python -c "import call_from_terminal as cft; cft.test_term_fun(${ip})"
# or
# fun_name='call_from_terminal'
# python -c "import ${fun_name} as cft; cft.test_term_fun(${ip})"
def test_term_fun(ip):
    print ip

这在bash中工作。

$ ip='"hi"' ; fun_name='call_from_terminal' 
$ python -c "import ${fun_name} as cft; cft.test_term_fun(${ip})"
hi