Python 从命令行运行函数

Python 从命令行运行函数,python,function,command-line,Python,Function,Command Line,我有以下代码: def hello(): return 'Hi :)' 如何直接从命令行运行它?python-c'来自myfile import hello;hello()“wheremyfile必须替换为Python脚本的basename。(例如,myfile.py变为myfile) 但是,如果hello()是Python脚本中的“永久”主入口点,那么通常的方法如下: def hello(): print "Hi :)" if __name__ == "__main__":

我有以下代码:

def hello():
    return 'Hi :)'

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

python-c'来自myfile import hello;hello()“
where
myfile
必须替换为Python脚本的basename。(例如,
myfile.py
变为
myfile

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

def hello():
    print "Hi :)"

if __name__ == "__main__":
    hello()
这允许您只需运行
python myfile.py
python-m myfile
即可执行脚本

这里有一些解释:
\uuuuu name\uuuuuuu
是一个特殊的Python变量,它保存当前正在执行的模块的名称,从命令行启动模块时除外,在这种情况下,模块将变成
“\uuuuu main\uuuuuuu”
只需放置
hello()
函数下面的某个地方,当您执行
python\u file.py

对于更整洁的解决方案,您可以使用以下方法:

if __name__ == '__main__':
    hello()
这样,只有在运行文件时才会执行函数,而不是在导入文件时。

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

或者,如果您不关心名称空间污染:

$ python -c 'from foo import *; print hello()'
中间立场:

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

无法从命令行运行此函数,因为它返回的值不会受到影响。您可以删除返回并改用print

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

然后导入您的文件,以便导入示例文件

然后使用示例\u file.hello()运行命令

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

可能没有单个命令方便,但这是一个很好的快速修复方法,可以从命令行为文件添加文本,并允许您使用python调用和执行文件。

类似于以下内容: 从_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

我编写了一个可以从bash命令行调用的快速小Python脚本。它采用要调用的模块、类和方法的名称以及要传递的参数。我将其称为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 install runp安装runp
安装runp软件包,则需要运行:

runp myfile.py hello


您可以在以下位置找到存储库:

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

echo print("hi:)") | python
以及管道文件

python < foo.py

我需要在命令行上使用各种python实用程序(范围、字符串等),并专门为此编写了工具。您可以使用它来丰富您的命令行使用体验:

 $ 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()
然后像这样使用:

$ python test.py hello
hi there!

$ python test.py goodbye
see ya later.
注意:目前在Python3中有一个错误,但是在Python2中效果很好

Edit:在我看来,一个更好的选择是谷歌的模块,它使传递函数参数变得更容易。它与
pip安装fire
一起安装。从他们的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
使用工具(pip安装python-c),然后简单地编写:

$ python-c foo 'hello()'
或者,如果python文件中没有函数名冲突:

$ python-c 'hello()'

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

下面是具有函数定义的奇偶函数.py文件

def OE(n):
    for a in range(n):
        if a % 2 == 0:
            print(a)
        else:
            print(a, "ODD")
现在,从下面的命令提示符调用相同的选项对我来说很有用

选项1 exe\python.exe-c的完整路径 “导入奇偶函数;奇偶函数。OE(100)”

选项2 exe\python.exe-c的完整路径 “从奇偶函数导入OE;OE(100)”


谢谢。

将此片段添加到脚本底部

def myfunction():
    ...


if __name__ == '__main__':
    globals()[sys.argv[1]]()
现在可以通过运行

python myscript.py myfunction
这是因为您正在将命令行参数(函数名称的字符串)传递到具有当前本地符号表的字典
locals
。最后的parantises将使函数被调用

更新:如果希望函数从命令行接受一个参数,可以像这样传入
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:])


可能您的意思是
打印“Hi:)”
而不是
返回“Hi:)”
def myfunction(mystring):
    print(mystring)


if __name__ == '__main__':
    globals()[sys.argv[1]](sys.argv[2])
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