我正在尝试从python脚本中运行一个shell命令,需要做几件事
1. shell命令是'hspice tran.deck>!tran.lis'2
.脚本应该在继续执行之前等待shell命令完成
3.我需要检查命令中的返回代码和
4.如果成功完成则捕获STDOUT否则捕获STDERR
我经历了子进程模块并尝试了一些事情,但无法找到完成上述所有操作的方法.
- 使用subprocess.call()我可以检查返回代码但不捕获输出.
- 使用subprocess.check_output()我可以捕获输出而不是代码.
- 使用subprocess.Popen()和Popen.communicate(),我可以捕获STDOUT和STDERR,但不能捕获返回码.
我不知道如何使用Popen.wait()或returncode属性.我也无法让Popen接受'>!' 或'|' 作为参数.
有人可以指点我正确的方向吗?我正在使用Python 2.7.1
编辑:使用以下代码
process = subprocess.Popen('ls | tee out.txt', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate()
if(process.returncode==0):
print out
else:
print err
Run Code Online (Sandbox Code Playgroud)
另外,我应该在process = line之后使用process.wait()还是默认等待?
Nik*_* B. 10
刚用完.returncode之后.communicate().另外,告诉Popen 你要运行的是shell命令,而不是原始命令行:
p = subprocess.Popen('ls | tee out.txt', shell=True, ...)
p.communicate()
print p.returncode
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7893 次 |
| 最近记录: |