我有这样的代码:

def hello():
    return '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可以在你路径的任何位置。

其他回答

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

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。

我需要在命令行上使用各种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安装runp包,这是一个运行的问题:

润普 myfile.py 你好

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

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

谢谢。

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