将 shell 命令的输出通过管道传输到 python 脚本 [英] Pipe output from shell command to a python script

查看:54
本文介绍了将 shell 命令的输出通过管道传输到 python 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to run a mysql command and set the output of that to be a variable in my python script.

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

Here is the shell command I'm trying to run:

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

这是python脚本:

Here is the python script:

#!/usr/bin/env python

import sys

def hello(variable):
    print variable

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

How would I accept the variable in the python script and have it print the output?

推荐答案

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

You need to read from stdin to retrieve the data in the python script e.g.

#!/usr/bin/env python

import sys

def hello(variable):
    print variable

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

如果您在这里要做的只是从 mysql 数据库中获取一些数据,然后使用 Python 对其进行操作,我将跳过将其管道化到脚本中,而只需使用 Python MySql 模块 进行 SQL 查询.

If all you want to do here is grab some data from a mysql database and then manipulate it with Python I would skip piping it into the script and just use the Python MySql module to do the SQL query.

这篇关于将 shell 命令的输出通过管道传输到 python 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆