管道输出从shell命令到python脚本

Dav*_*542 29 python unix

我想运行一个mysql命令,并将其输出设置为我的python脚本中的变量.

这是我正在尝试运行的shell命令:

$ mysql my_database --html -e "select * from limbs" | ./script.py
Run Code Online (Sandbox Code Playgroud)

这是python脚本:

#!/usr/bin/env python

import sys

def hello(variable):
    print variable
Run Code Online (Sandbox Code Playgroud)

我如何接受python脚本中的变量并让它打印输出?

Jon*_*age 28

您需要从stdin读取以检索python脚本中的数据,例如

#!/usr/bin/env python

import sys

def hello(variable):
    print variable

data = sys.stdin.read()
hello(data)
Run Code Online (Sandbox Code Playgroud)

如果你想在这里做的就是从mysql数据库中获取一些数据,然后用Python操作它,我会跳过它到脚本中,然后使用Python MySql模块来执行SQL查询.

  • 看起来 shebang 很重要,这就是为什么其他示例都不起作用的原因。没有它,它就会永远挂起。 (3认同)

mst*_*ger 20

如果希望脚本的行为与许多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
Run Code Online (Sandbox Code Playgroud)


C0d*_*ker 10

将一个命令的输出传递给pytho脚本时,它将转到sys.stdin.您可以像文件一样从sys.stdin中读取.例:

import sys

print sys.stdin.read()
Run Code Online (Sandbox Code Playgroud)

该程序从字面上输出其输入.

  • +1提及"就像一个文件",这将有希望引导OP意识到他也可以做​​一些事情,比如"for line in sys.stdin:"等. (2认同)

小智 9

您可以使用命令行工具xargs

echo 'arg1' | xargs python script.py

arg1现在可以从sys.argv[1]in访问script.py


nls*_*bch 7

由于这个答案在搜索时前谷歌上弹出piping data to a python script,我想补充的另一种方法,我在发现J. Beazley的Python的食谱比使用搜索一个少“坚韧不拔”的形式给出后sys。IMO,即使对新用户也更加 Pythonic 和不言自明。

import fileinput
with fileinput.input() as f_input:
    for line in f_input:
        print(line, end='')
Run Code Online (Sandbox Code Playgroud)

这种方法也适用于结构如下的命令:

$ 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.
Run Code Online (Sandbox Code Playgroud)

如果您需要更复杂的解决方案,您可以进行组合argparsefileinput martinth 的本要点所示

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)
Run Code Online (Sandbox Code Playgroud)

``


not*_*bit 5

也适用于Windows及以上的单行代码正在使用,如下所示:Python 3.10.3sys.stdin.read()

echo 'Hello!' | python -c "import sys;d=sys.stdin.read(); print('{}\n'.format(d))"
Run Code Online (Sandbox Code Playgroud)