从命令行运行功能

问题:从命令行运行功能

我有以下代码:

def hello():
    return 'Hi :)'

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

I have this code:

def hello():
    return 'Hi :)'

How would I run this directly from the command line?


回答 0

使用-c (command)参数(假设您的文件名为foo.py):

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

或者,如果您不关心命名空间污染,请执行以下操作:

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

和中间立场:

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

With the -c (command) argument (assuming your file is named foo.py):

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

Alternatively, if you don’t care about namespace pollution:

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

And the middle ground:

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

回答 1

只需将其hello()放在函数下方,它将在您执行时执行python your_file.py

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

if __name__ == '__main__':
    hello()

这样,仅当您运行文件时才执行该功能,而不是在导入文件时执行该功能。

Just put hello() somewhere below the function and it will execute when you do python your_file.py

For a neater solution you can use this:

if __name__ == '__main__':
    hello()

That way the function will only be executed if you run the file, not when you import the file.


回答 2

python -c 'from myfile import 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__"

python -c 'from myfile import hello; hello()' where myfile must be replaced with the basename of your Python script. (E.g., myfile.py becomes myfile).

However, if hello() is your “permanent” main entry point in your Python script, then the usual way to do this is as follows:

def hello():
    print "Hi :)"

if __name__ == "__main__":
    hello()

This allows you to execute the script simply by running python myfile.py or python -m myfile.

Some explanation here: __name__ is a special Python variable that holds the name of the module currently being executed, except when the module is started from the command line, in which case it becomes "__main__".


回答 3

我编写了一个快速的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\)

请注意最后一个转义括号以将元组作为Second方法的唯一参数传递的示例。

如果为该方法所需的参数传递的参数太少,则会出现错误。如果您通过太多,它将忽略额外费用。该模块必须在当前工作文件夹中,将PyRun放置在路径中的任何位置。

I wrote a quick little Python script that is callable from a bash command line. It takes the name of the module, class and method you want to call and the parameters you want to pass. I call it PyRun and left off the .py extension and made it executable with chmod +x PyRun so that I can just call it quickly as follow:

./PyRun PyTest.ClassName.Method1 Param1

Save this in a file called 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)

Here is a sample module to show how it works. This is saved in a file called 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")

Try running these examples:

./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\)

Note the last example of escaping the parentheses to pass in a tuple as the only parameter to the Second method.

If you pass too few parameters for what the method needs you get an error. If you pass too many, it ignores the extras. The module must be in the current working folder, put PyRun can be anywhere in your path.


回答 4

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

def myfunction():
    ...


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

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

python myscript.py myfunction

之所以有效,是因为您要将命令行参数(函数名称的字符串)传递给locals,该字典具有当前本地符号表。最后的括号将使函数被调用。

更新:如果您希望函数从命令行接受参数,则可以这样传递sys.argv[2]

def myfunction(mystring):
    print mystring


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

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

add this snippet to the bottom of your script

def myfunction():
    ...


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

You can now call your function by running

python myscript.py myfunction

This works because you are passing the command line argument (a string of the function’s name) into locals, a dictionary with a current local symbol table. The parantheses at the end will make the function be called.

update: if you would like the function to accept a parameter from the command line, you can pass in sys.argv[2] like this:

def myfunction(mystring):
    print mystring


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

This way, running python myscript.py myfunction "hello" will output hello.


回答 5

让我们自己简化一点,只使用一个模块…

尝试: pip install 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.

注意:目前Python 3中存在一个错误,但与Python 2配合使用时效果很好。

编辑:我认为是一个更好的选择,是Google 触发的模块,这也使得传递函数参数变得容易。它与一起安装pip install 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

Let’s make this a little easier on ourselves and just use a module…

Try: pip install compago

Then write:

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

Then use like so:

$ python test.py hello
hi there!

$ python test.py goodbye
see ya later.

Note: There’s a bug in Python 3 at the moment, but works great with Python 2.

Edit: An even better option, in my opinion is the module fire by Google which makes it easy to also pass function arguments. It is installed with pip install fire. From their GitHub:

Here’s a simple example.

import fire

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

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

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

Then, from the command line, you can run:

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

回答 6

有趣的是,如果目标是打印到命令行控制台或执行其他一些分钟的python操作,则可以将输入通过管道传递到python解释器中,如下所示:

echo print("hi:)") | python

以及管道文件

python < foo.py

*请注意,扩展名不必一定是.py才能正常工作。**还请注意,对于bash而言,您可能需要转义字符

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

Interestingly enough, if the goal was to print to the command line console or perform some other minute python operation, you can pipe input into the python interpreter like so:

echo print("hi:)") | python

as well as pipe files..

python < foo.py

*Note that the extension does not have to be .py for the second to work. **Also note that for bash you may need to escape the characters

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

回答 7

如果安装runp软件包时pip install runp需要运行:

runp myfile.py hello

您可以在以下位置找到存储库:https : //github.com/vascop/runp

If you install the runp package with pip install runp its a matter of running:

runp myfile.py hello

You can find the repository at: https://github.com/vascop/runp


回答 8

我需要在命令行上使用各种python实用程序(范围,字符串等),并为此专门编写了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

I had a requirement of using various python utilities (range, string, etc.) on the command line and had written the tool pyfunc specifically for that. You can use it to enrich you command line usage experience:

 $ 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

回答 9

始终可以使用python命令在命令行中输入python

然后导入您的文件,以便导入example_file

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

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

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

It is always an option to enter python on the command line with the command python

then import your file so import example_file

then run the command with example_file.hello()

This avoids the weird .pyc copy function that crops up every time you run python -c etc.

Maybe not as convenient as a single-command, but a good quick fix to text a file from the command line, and allows you to use python to call and execute your file.


回答 10

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

Something like this: 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

This works in bash.

$ ip='"hi"' ; fun_name='call_from_terminal' 
$ python -c "import ${fun_name} as cft; cft.test_term_fun(${ip})"
hi

回答 11

下面是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“从Odd_Even_function import OE; OE(100)”的完整路径

谢谢。

Below is the Odd_Even_function.py file that has the definition of the function.

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

Now to call the same from Command prompt below are the options worked for me.

Options 1 Full path of the exe\python.exe -c “import Odd_Even_function; Odd_Even_function.OE(100)”

Option 2 Full path of the exe\python.exe -c “from Odd_Even_function import OE; OE(100)”

Thanks.


回答 12

此函数无法从命令行运行,因为它返回的值将不可用。您可以删除退货并改为使用打印

This function cannot be run from the command line as it returns a value which will go unhanded. You can remove the return and use print instead


回答 13

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

$ python-c foo 'hello()'

或在python文件中没有函数名冲突的情况下:

$ python-c 'hello()'

Use the python-c tool (pip install python-c) and then simply write:

$ python-c foo 'hello()'

or in case you have no function name clashes in your python files:

$ python-c 'hello()'

回答 14

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

First you have to call the function as they told you or the founction will display nothing in the output, after that save the file and copy the path of the file by right click to the folder of the file and click on”copy file” then go to terminal and write: – cd “the path of the file” – python “name of the file for example (main.py)” after that it will display the output of your code.


回答 15

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

Make your life easier, install Spyder. Open your file then run it (click the green arrow). Afterwards your hello() method is defined and known to the IPython Console, so you can call it from the console.