我有这样的代码:

def hello():
    return 'Hi :)'

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


当前回答

让我们简单一点,使用一个模块。

尝试:pip安装compago

然后写:

import compago
app = compago.Application()

@app.command
def hello():
    print "hi there!"

@app.command
def goodbye():
    print "see ya later."

if __name__ == "__main__":
    app.run()

然后用like so:

$ python test.py hello
hi there!

$ python test.py goodbye
see ya later.

注意:目前在Python 3中有一个bug,但在Python 2中工作得很好。

编辑:一个更好的选择,在我看来是模块fire谷歌,它可以很容易地传递函数参数。它安装有pip安装火。来自他们的GitHub:

这里有一个简单的例子。

import fire

class Calculator(object):
  """A simple calculator class."""

  def double(self, number):
    return 2 * number

if __name__ == '__main__':
  fire.Fire(Calculator)

然后,从命令行,你可以运行:

python calculator.py double 10  # 20
python calculator.py double --number=15  # 30

其他回答

此函数不能从命令行运行,因为它返回的值将不被传递。您可以删除返回并使用print代替

首先,你必须像他们告诉你的那样调用函数,否则该函数将在输出中不显示任何内容,然后保存文件并通过右键单击文件的文件夹复制文件的路径,然后单击“复制文件”,然后转到终端并写入: - CD文件的路径 - python "文件名为例(main.py)" 之后,它将显示代码的输出。

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

"""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()'

有趣的是,如果目标是打印到命令行控制台或执行其他一些minute python操作,你可以像这样将输入管道到python解释器:

echo print("hi:)") | python

以及管道文件..

python < foo.py

*请注意,第二个扩展名不一定是.py。 **还请注意,对于bash,您可能需要转义字符

echo print\(\"hi:\)\"\) | python