Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

python - How to handle random bytestream when executing shell commands?

I want to run arbitrary commands in the shell and get stdout and stderr, for example like this:

cmd = subprocess.run(command, shell=True, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = cmd.stdout
stderr = cmd.stderr

However, stdout and stderr might contain random bytestreams. This leads to errors like this:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfd in position 135: invalid start byte

How can I handle this? Stuff like ? would be ok as result.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This error is caused by universal_newlines=True causing your data to be read as text rather than as binary content. Remove that argument.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...