我想运行一个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脚本中的变量并让它打印输出?
发布于 2012-06-20 05:44:46
您需要从stdin读取以检索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查询。
发布于 2012-06-20 07:53:21
如果希望脚本的行为与许多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
发布于 2012-06-20 05:44:29
当您通过管道将一个命令的输出传输到pytho脚本时,它将传输到sys.stdin。您可以像读取文件一样从sys.stdin读取数据。示例:
import sys
print sys.stdin.read()
这个程序逐字输出它的输入。
https://stackoverflow.com/questions/11109859
复制相似问题