擅长:python、mysql、java
<p>是的,这是可能的。下面是我为一个测试工具编写的一个函数,用于对Python shell脚本进行单元测试。</p>
<pre><code>def testrun(cmdline):
try:
cmdout, cmderr = "",""
cmdp = Popen(cmdline, shell=True,stdout=PIPE, stderr=PIPE)
cmdout,cmderr = cmdp.communicate()
retcode = cmdp.wait()
if retcode < 0:
print >>sys.stderr, "Child was terminated by signal", -retcode
else:
return (retcode,cmdout,cmderr)
except OSError, e:
return (e,cmdout,cmderr)
</code></pre>
<p>函数返回一个元组,该元组包含由<code>sys.exit()</code>发出的shell返回代码、标准输出文本和标准错误输出文本。它们都是文本字符串,因此在处理之前需要使用<code>splitlines</code>将它们分成几行。</p>
<p>如果您真的需要逐行与输出交互,那么最好使用<a href="http://www.noah.org/wiki/Pexpect" rel="nofollow">pexpect</a>,而不是<code>subprocess</code>模块。</p>