我有这样的代码:

def hello():
    return 'Hi :)'

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


从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()

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


使用-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()'

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


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

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

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

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

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


就像这样: 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

我写了一个快速的小Python脚本,可以从bash命令行调用。它接受你想要调用的模块、类和方法的名称,以及你想要传递的参数。我把它叫做PyRun,并去掉了.py扩展名,让它可以用chmod +x PyRun执行,这样我就可以像下面这样快速地调用它:

./PyRun PyTest.ClassName.Method1 Param1

将其保存在一个名为PyRun的文件中

#!/usr/bin/env python
#make executable in bash chmod +x PyRun

import sys
import inspect
import importlib
import os

if __name__ == "__main__":
    cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))
    if cmd_folder not in sys.path:
        sys.path.insert(0, cmd_folder)

    # get the second argument from the command line      
    methodname = sys.argv[1]

    # split this into module, class and function name
    modulename, classname, funcname = methodname.split(".")

    # get pointers to the objects based on the string names
    themodule = importlib.import_module(modulename)
    theclass = getattr(themodule, classname)
    thefunc = getattr(theclass, funcname)

    # pass all the parameters from the third until the end of 
    # what the function needs & ignore the rest
    args = inspect.getargspec(thefunc)
    z = len(args[0]) + 2
    params=sys.argv[2:z]
    thefunc(*params)

下面是一个示例模块来展示它是如何工作的。它被保存在一个名为PyTest.py的文件中:

class SomeClass:
 @staticmethod
 def First():
     print "First"

 @staticmethod
 def Second(x):
    print(x)
    # for x1 in x:
    #     print x1

 @staticmethod
 def Third(x, y):
     print x
     print y

class OtherClass:
    @staticmethod
    def Uno():
        print("Uno")

试着运行这些例子:

./PyRun PyTest.SomeClass.First
./PyRun PyTest.SomeClass.Second Hello
./PyRun PyTest.SomeClass.Third Hello World
./PyRun PyTest.OtherClass.Uno
./PyRun PyTest.SomeClass.Second "Hello"
./PyRun PyTest.SomeClass.Second \(Hello, World\)

请注意最后一个转义圆括号的例子,将一个元组作为第二个方法的唯一参数传递给第二个方法。

如果传递的参数少于方法所需的参数,就会报错。如果你传递太多,它会忽略额外的部分。该模块必须在当前工作文件夹中,放置PyRun可以在你路径的任何位置。


如果你用pip安装runp包,这是一个运行的问题:

润普 myfile.py 你好

您可以在https://github.com/vascop/runp上找到该存储库


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

echo print("hi:)") | python

以及管道文件..

python < foo.py

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

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

我需要在命令行上使用各种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

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

尝试: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-c工具(pip install python-c),然后简单地写:

$ python-c foo 'hello()'

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

$ python-c 'hello()'

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


下面是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)“

谢谢。


将此代码片段添加到脚本底部

def myfunction():
    ...


if __name__ == '__main__':
    globals()[sys.argv[1]]()

现在可以通过运行来调用函数

python myscript.py myfunction

这是因为您将命令行参数(函数名的字符串)传递到locals中,locals是一个包含当前局部符号表的字典。最后的parantheses将使函数被调用。

更新:如果你想让函数从命令行接受一个参数,你可以传入sys。Argv[2]像这样:

def myfunction(mystring):
    print(mystring)


if __name__ == '__main__':
    globals()[sys.argv[1]](sys.argv[2])

这样,运行python myscript.py myfunction "hello"将输出hello。


让您的生活更轻松,安装Spyder。打开文件,然后运行它(单击绿色箭头)。之后,您的hello()方法被定义并被IPython控制台所知道,因此您可以从控制台调用它。


我们可以这样写。我在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

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

"""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