我有这样的代码:

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

其他回答

在命令行上使用python命令输入python始终是一个选项

然后导入您的文件,因此导入example_file

然后使用example_file.hello()运行命令

这避免了每次运行python -c等时突然出现的奇怪的.pyc复制函数。

也许不像单个命令那么方便,但是从命令行文本文件的一个很好的快速修复,并允许您使用python来调用和执行您的文件。

使用python-c工具(pip install python-c),然后简单地写:

$ python-c foo 'hello()'

或者如果你的python文件中没有函数名冲突:

$ python-c 'hello()'

下面是Odd_Even_function.py文件,其中包含函数的定义。

def OE(n):
    for a in range(n):
        if a % 2 == 0:
            print(a)
        else:
            print(a, "ODD")

现在从命令提示符下面调用相同的选项为我工作。

选项1 exe\python.exe -c的完整路径 “进口Odd_Even_function;Odd_Even_function.OE(100)“

选项2 exe\python.exe -c的完整路径 from Odd_Even_function import OE;OE(100)“

谢谢。

我需要在命令行上使用各种python实用程序(range, string等),并为此专门编写了pyfunc工具。你可以用它来丰富你的命令行使用经验:

 $ pyfunc -m range -a 1 7 2
 1
 3
 5

 $ pyfunc -m string.upper -a test
 TEST

 $ pyfunc -m string.replace -a 'analyze what' 'what' 'this'
 analyze this

我们可以这样写。我在python-3.7.x中使用过

import sys

def print_fn():
    print("Hi")

def sum_fn(a, b):
    print(a + b)

if __name__ == "__main__":
    args = sys.argv
    # args[0] = current file
    # args[1] = function name
    # args[2:] = function args : (*unpacked)
    globals()[args[1]](*args[2:])

python demo.py print_fn
python demo.py sum_fn 5 8