我想运行 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 脚本中的变量并让它打印输出?
最佳答案
您需要从标准输入读取数据以检索 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 查询。
关于python - 将 shell 命令的输出通过管道传输到 python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11109859/