Python使用subprocess执行shell命令

2023-05-16

import subprocess
import time

cmd = "XX"
svnlog1 = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
time.sleep(0.01) #执行命令cmd, 0.01秒后结束shell子进程,停止执行命令。
svnlog1.terminate()
svnlog1.wait()
if svnlog1.stderr:
    print(svnlog1.stderr.readlines())
    print(svnlog1.stderr.read())
else:
    print(svnlog1.stdout.readlines())
result1 = svnlog1.stdout.readlines()
print(svnlog1.stdout.readlines())
print(svnlog1.stderr.read())
print("poll:"+str(svnlog1.poll()))
print("wait:"+str(svnlog1.wait()))
print("returncode:"+str(svnlog1.returncode))
print("pid:"+str(svnlog1.pid))
print("communicate:"+str(svnlog1.communicate()))
for i in result1:#Python 3里面,str在内存里是unicode表示的,需遍历数组并解码
#    print(i)
    print(i.decode(encoding='utf-8', errors='ignore'))

问题:'utf-8' codec can't decode byte 0xe5...

Traceback (most recent call last):

File "test_subprocess.py", line 28, in <module>

print(i.decode('utf-8'))

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe5 in position 83: unexpected end of data

解决方案:增加errors='ignore'

i.decode(encoding='utf-8', errors='ignore')

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python使用subprocess执行shell命令 的相关文章

随机推荐