接触python不久,最近遇到了棘手的问题。 关于subprocess.Popen
以ret=subprocess.popen(cmd,shell=true,stdout=subprocess.PIPE )的形式在shell上运行cmd命令
在ret.returncode中获取返回值
通过retout=ret.comunication () [0]获取输出
问题在于cmd的格式、返回值和返回输出。
如果cmd有重定向操作,retoutd将无法获得cmd的输出;
如果在cmd中指定后台执行,则ret.returncode无法获取cmd的返回值,只能获取shell执行命令的返回值
如果cmd有重定向和后台运行,ret.returncode和retout将无法获取cmd的返回值和输出
例如:
test.sh:
echo 'this is test.sh '
exit 127
test.py:
cmd=' '
ret=subprocess.popen(cmd,shell=true,stdout=PIPE ) )。
retout=ret.comunication (
打印(ret.return code,retout ) )。
cmd='test.sh '结果输出: 127 this is test.sh
cmd='test.sh '结果输出:0 this is test.sh
cmd='test.sh abc.txt '结果输出: 127
cmd='test.sh abc.txt '结果输出: 0