2010-10-21 59 views
193

功能我有下面的代碼在我的文件:的Python:從命令行

def hello(): 
    return 'Hi :)' 

我怎麼會在命令行中運行這個?

+9

也許你的意思是'打印'嗨:)''而不是'return'嗨:)''。 – 2010-10-21 11:56:04

+0

所有這些的重複:http://stackoverflow.com/search?q=%5Bpython%5D+run+command+line – 2010-10-21 13:39:58

回答

318

隨着-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()' 
+12

我注意到,在Windows外殼上,你需要一個雙引號而不是單引號。 '$ python -c「import foo; foo.hello()」' – 2016-06-01 12:59:25

+1

如果文件不在本地目錄或PYTHONPATH中,該怎麼辦? – Konstantin 2017-07-07 14:32:29

+0

在Ubuntu Linux上,如果您從Qt應用程序中運行命令,則還必須使用雙引號。 – 2017-07-17 11:52:51

38

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__是一個包含模塊的當前正在執行,除了當模塊命令行,在這種情況下,它變成"__main__"開始的名字一個特殊的Python變量。

+0

'python -m foo -c'foo.bar()''有什麼區別?'和'python -c'import foo; foo.bar()''?我得到了不同的行爲,在第一種情況下,似乎忽略了-c參數。 – Abram 2017-06-17 07:56:30

69

只要把hello()以下功能的地方,當你做python your_file.py

它將執行對於一個整潔的解決方案,您可以使用此:

if __name__ == '__main__': 
    hello() 

這樣,如果你運行該功能僅被執行該文件,而不是在導入文件時。

+1

這應該是正確的答案 – zon7 2017-11-08 11:41:32

+0

如果'hello()'接受應該由命令行提供的參數? – Anonymous 2018-02-10 02:29:07

+0

在這種情況下,您可以發送'sys.argv'到方法。或者從hello方法訪問它 – Wolph 2018-02-10 08:48:15

0

該函數無法從命令行運行,因爲它返回的值將不受限制。您可以刪除的回報,用打印代替

0

它始終是在命令行中輸入蟒蛇用命令蟒蛇

然後導入您的文件,以便進口example_file

然後運行一個選項與example_file.hello()

這樣就避免了每次作物了怪異的.pyc文件複製功能命令你運行python -c等

也許不如單一命令那麼方便,但是可以很好地快速修復命令行中的文件,並允許您使用python來調用和執行文件。

0

事情是這樣的: 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 
17

我寫了一個快速的小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放在您的路徑中的任何位置。

+2

這很好,但它不是真正的答案。 – 2015-03-18 19:31:12

+8

我不同意;這正是問題。他問你如何從一個文件運行一個函數,而這正是它的功能。 – 2015-03-20 00:56:13

+0

你能解釋一下關於cmd_folder的功能嗎? – RyanDay 2018-01-26 22:44:51

4

有趣的是,如果我們的目標是要打印到命令行控制檯或執行一些其他的Python操作,你可以輸入python解釋器如下:

echo print("hi:)") | python 

以及管道文件..

python < foo.py 

*請注意,擴展不必是的.py第二工作。 **另請注意,bash,那麼你可能需要轉義字符

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

考慮到foo.py和hello()的例子,這就是人們如何使用它與上述想法。 'echo import foo; foo.hello()| python' – 2016-05-31 09:27:36

+0

有什麼辦法可以通過這個方法傳遞命令行參數嗎? – iamseiko 2017-04-12 18:46:21

+0

FWIW,對於第三個例子,下面略微清晰:'echo'print(「hi :)」)'| python' – user3166580 2017-08-31 11:09:55

1

我不得不在命令行中使用各種蟒蛇公用事業(範圍,字符串等)的要求,並已書面工具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 
2

讓我們對自己稍微簡單一點,然後使用模塊...

嘗試: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 bug的那一刻,但與Python的偉大工程2.

編輯:一個更好的選擇,在我看來是谷歌的模塊fire,這使得它也容易傳遞函數參數。它與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 
0

使用python-c工具(PIP安裝python-C),然後簡單地寫:

$ python-c foo 'hello()' 

或者如果你的Python文件中沒有函數名衝突:

$ python-c 'hello()'