2012-06-19 90 views
18

我想運行一個mysql命令並將其輸出設置爲我的python腳本中的一個變量。從shell命令管道輸出到python腳本

這裏是我試圖運行shell命令:

$ mysql my_database --html -e "select * from limbs" | ./script.py 

下面是python腳本:

#!/usr/bin/env python 

import sys 

def hello(variable): 
    print variable 

我怎麼會接受的python腳本變量,並把它打印輸出?

回答

19

您需要從標準輸入讀取才能檢索python腳本中的數據,例如

#!/usr/bin/env python 

import sys 

def hello(variable): 
    print variable 

data = sys.stdin.read() 
hello(data) 

如果你想在這裏做的是從MySQL數據庫中抓取一些數據,然後與Python操縱它我會跳過它管道到腳本,只需使用the Python MySql module做SQL查詢。

+0

+1用於提示mysql-python。 – abarnert

9

當您將一個命令的輸出傳遞給pytho腳本時,它會轉至sys.stdin。你可以像sys.stdin一樣讀取文件。例如:

import sys 

print sys.stdin.read() 

該程序從字面上輸出其輸入。

+1

+1提「就像一個文件」,希望這將導致意識到自己也可以做這樣的事情「爲OP line in sys.stdin:「等。 – abarnert

16

如果你希望你的腳本的行爲就像許多UNIX命令行工具,接受管道或文件名作爲第一個參數,你可以使用以下命令:

#!/usr/bin/env python 
import sys 

# use stdin if it's full               
if not sys.stdin.isatty(): 
    input_stream = sys.stdin 

# otherwise, read the given filename            
else: 
    try: 
     input_filename = sys.argv[1] 
    except IndexError: 
     message = 'need filename as first argument if stdin is not full' 
     raise IndexError(message) 
    else: 
     input_stream = open(input_filename, 'rU') 

for line in input_stream: 
    print line # do something useful with each line 
2

由於這個答案在上谷歌彈出搜索piping data to a python script時頂部,我想添加另一種方法,我找到了J. Beazley's Python Cookbook後找到一個比使用sys更少的「砂礫」的方法。國際海事組織,甚至對新用戶來說更加pythonic和不言自明。

import fileinput 
with fileinput.input() as f_input: 
    for line in f_input: 
     print(line, end='') 

這種方法也適用於結構類似這樣的命令:

$ ls | ./filein.py   # Prints a directory listing to stdout. 
$ ./filein.py /etc/passwd # Reads /etc/passwd to stdout. 
$ ./filein.py < /etc/passwd # Reads /etc/passwd to stdout. 
+0

收到錯誤用這種方法(使用Python 2.7) 回溯(最近通話最後一個): 文件 「./pipetome.py」,4號線,在 與fileinput.input()作爲f_input: AttributeError的: FileInput實例沒有屬性'__exit__' –

+0

以上僅在Python3中測試過 - 可能不是'with'嘗試'f_input = fileinput.input()'? – nlsdfnbch