我想编写一个函数来执行shell命令并将其输出作为字符串返回,无论是错误还是成功消息.我只想获得与命令行相同的结果.
什么是代码示例会做这样的事情?
例如:
def run_command(cmd):
# ??????
print run_command('mysqladmin create test -uroot -pmysqladmin12')
# Should output something like:
# mysqladmin: CREATE DATABASE failed; error: 'Can't create database 'test'; database exists'
Run Code Online (Sandbox Code Playgroud) 我的python脚本使用subprocess来调用非常嘈杂的linux实用程序.我想将所有输出存储到日志文件中并向用户显示一些输出.我认为以下内容可行,但在实用程序产生大量输出之前,输出不会显示在我的应用程序中.
#fake_utility.py, just generates lots of output over time
import time
i = 0
while True:
print hex(i)*512
i += 1
time.sleep(0.5)
#filters output
import subprocess
proc = subprocess.Popen(['python','fake_utility.py'],stdout=subprocess.PIPE)
for line in proc.stdout:
#the real code does filtering here
print "test:", line.rstrip()
Run Code Online (Sandbox Code Playgroud)
我真正想要的行为是过滤器脚本在从子进程接收时打印每一行.Sorta就像tee使用python代码一样.
我错过了什么?这甚至可能吗?
更新:
如果将a sys.stdout.flush()添加到fake_utility.py,则代码在python 3.1中具有所需的行为.我正在使用python 2.6.您会认为使用proc.stdout.xreadlines()将与py3k一样工作,但事实并非如此.
更新2:
这是最小的工作代码.
#fake_utility.py, just generates lots of output over time
import sys, time
for i in range(10):
print i
sys.stdout.flush()
time.sleep(0.5)
#display out put line by …Run Code Online (Sandbox Code Playgroud) 是否可以让bash脚本自动处理通常以默认操作呈现给用户的提示?目前我正在使用bash脚本来调用内部工具,该工具将向用户显示提示(提示Y/N)以完成操作,但是我写的脚本需要完全"不干涉",所以我需要一种方法发送Y|N到提示,以允许程序继续执行.这可能吗?
我有一个名为的脚本1st.py,它创建了一个REPL(read-eval-print-loop):
print "Something to print"
while True:
r = raw_input()
if r == 'n':
print "exiting"
break
else:
print "continuing"
Run Code Online (Sandbox Code Playgroud)
然后我1st.py使用以下代码启动:
p = subprocess.Popen(["python","1st.py"], stdin=PIPE, stdout=PIPE)
Run Code Online (Sandbox Code Playgroud)
然后尝试了这个:
print p.communicate()[0]
Run Code Online (Sandbox Code Playgroud)
它失败了,提供了这个追溯:
Traceback (most recent call last):
File "1st.py", line 3, in <module>
r = raw_input()
EOFError: EOF when reading a line
Run Code Online (Sandbox Code Playgroud)
你能解释一下这里发生了什么吗?当我使用时p.stdout.read(),它会永远挂起.