从shell命令到python脚本的管道输出
我想运行一个从shell命令到python脚本的管道输出,python,unix,Python,Unix,我想运行一个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脚本中接受变量并让它打印输出?将一个命令的输出通过管道传输到
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脚本时,它将转到sys.stdin。您可以像读取文件一样读取sys.stdin。例如:
import sys
print sys.stdin.read()
这个程序直接输出它的输入。您需要从stdin中读取以检索python脚本中的数据,例如
#!/usr/bin/env python
import sys
def hello(variable):
print variable
data = sys.stdin.read()
hello(data)
如果您只想从mysql数据库中获取一些数据,然后使用Python对其进行操作,我将跳过将其管道化到脚本中,而只使用它来执行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
由于在搜索
管道数据到python脚本时,Google会在顶部弹出这个答案,因此我想添加另一个方法,在搜索比使用sys
更不“粗糙”的方法后,我在中找到了这个方法。在我看来,这更像是一种通俗易懂的语言,甚至对新用户也是如此
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.
```我在尝试将bash命令通过管道传输到我没有编写的python脚本(并且不想修改以接受sys.stdin
)时遇到了这个问题。我发现这里提到的进程替换()工作得很好
前。
some_script.py-arg1您可以使用命令行工具xargs
echo'arg1'| xargs python script.py
arg1
现在可以从sys.argv[1]
在script.py
+1中访问,因为它提到了“就像一个文件”,这将有希望使OP意识到他也可以做类似于“for line in sys.stdin:”,等等的事情。使用此方法(使用python 2.7)获取错误回溯(最近一次调用:file)“/pipetome.py”,第4行,以fileinput.input()作为f_输入:AttributeError:fileinput实例没有属性'exit'。以上仅在Python3中测试-可能不是使用
tryf_输入=fileinput.input()
?但是如何区分args和stdin,例如发送邮件到xxx@xxx.com-主题“passwd”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)