簡體   English   中英

將 shell 命令的輸出通過管道傳輸到 python 腳本

[英]Pipe output from shell command to a python script

我想運行一個mysql命令並將它的輸出設置為我的 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 腳本中的變量並讓它打印輸出?

您需要從 stdin 讀取以檢索 python 腳本中的數據,例如

#!/usr/bin/env python

import sys

def hello(variable):
    print variable

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

如果您想做的只是從 mysql 數據庫中獲取一些數據,然后使用 Python 對其進行操作,我將跳過將其管道化到腳本中,而僅使用Python MySql 模塊來執行 SQL 查詢。

如果您希望您的腳本像許多 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

當您將一個命令的輸出通過管道傳輸到 pytho 腳本時,它會轉到 sys.stdin。 您可以像讀取文件一樣從 sys.stdin 讀取。 例子:

import sys

print sys.stdin.read()

這個程序從字面上輸出它的輸入。

由於在搜索piping data to a python script時這個答案會在谷歌的頂部彈出,我想添加另一種方法,我在J. Beazley 的 Python Cookbook 中找到了一種比使用更不“堅韌”的方法后sys IMO,即使對新用戶也更加 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.

如果您需要更復雜的解決方案,您可以組合argparsefileinput ,如fileinput本要點所示

import argpase
import fileinput

if __name__ == '__main__':
    parser = ArgumentParser()
    parser.add_argument('--dummy', help='dummy argument')
    parser.add_argument('files', metavar='FILE', nargs='*', help='files to read, if empty, stdin is used')
    args = parser.parse_args()

    # If you would call fileinput.input() without files it would try to process all arguments.
    # We pass '-' as only file when argparse got no files which will cause fileinput to read from stdin
    for line in fileinput.input(files=args.files if len(args.files) > 0 else ('-', )):
        print(line)

``

可以使用命令行工具xargs

echo 'arg1' | xargs python script.py

現在可以從script.py sys.argv[1]訪問arg1

我偶然發現了這一點,試圖將 bash 命令通過管道傳輸到我沒有編寫的 python 腳本(並且不想修改以接受sys.stdin )。 我發現這里提到的進程替換( https://superuser.com/questions/461946/can-i-use-pipe-output-as-a-shell-script-argument )可以正常工作。

前任。 some_script.py -arg1 <(bash command)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM