简体   繁体   English

python运行bash命令得到错误的结果

[英]python run bash command get bad result

Hi I'm trying to run this bash cmd on python 3.2. 嗨,我想在python 3.2上运行这个bash cmd。 Here is the python code: 这是python代码:

message = '\\x61'
shell_command = "echo -n -e '" + message + "' | md5"
print(shell_command)
event = Popen(shell_command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
print(event.communicate())

this gave me next result: 这给了我下一个结果:
echo -n -e '\\x61' | echo -n -e'\\ x61'| md5 MD5
(b'713b2a82dc713ef273502c00787f9417\\n', None) (b'713b2a82dc713ef273502c00787f9417 \\ n',无)
But when I run this printed cmd in bash, I get different result: 但是当我在bash中运行这个打印的cmd时,我会得到不同的结果:
0cc175b9c0f1b6a831c399e269772661 0cc175b9c0f1b6a831c399e269772661

Where I did mistake? 我错在哪里?

The key to this problem is when you say: 这个问题的关键是当你说:

But when I run this printed cmd in bash... 但是当我在bash中运行这个印刷的cmd时......

The Popen function of the subprocess module does not necessarily use bash, it may use some other shell such as /bin/sh which will not necessarily handle the echo command identically to bash. 子进程模块的Popen函数不一定使用bash,它可能使用一些其他shell,例如/bin/sh ,它不一定像bash一样处理echo命令。 On my system running the command in bash produces the same result as you get: 在我的系统上,在bash中运行命令产生的结果与你得到的结果相同:

$ echo -n -e '\x61' | md5sum
0cc175b9c0f1b6a831c399e269772661  -

But if I run the command in /bin/sh I get: 但是如果我在/bin/sh运行命令,我得到:

$ echo -n -e '\x61' | md5sum
20b5b5ca564e98e1fadc00ebdc82ed63  -

This is because /bin/sh on my system doesn't understand the -e option nor does it understand the \\x escape sequence. 这是因为我的系统上的/bin/sh不理解-e选项,也不理解\\x转义序列。

If I run your code in python I get the same result as if I'd used /bin/sh : 如果我在python中运行你的代码,我会得到与我使用/bin/sh相同的结果:

>>> cmd = "echo -n -e '\\x61' | md5sum"
>>> event = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT)
>>> print event.communicate()
('20b5b5ca564e98e1fadc00ebdc82ed63  -\n', None)

You dont need to use echo to pass data. 您不需要使用echo传递数据。 You can do it directly with python, ie: 你可以直接用python做,即:

Popen('/usr/bin/md5sum', shell=False, stdin=PIPE).communicate('\x61')

From the docs : 来自文档

communicate() returns a tuple (stdoutdata, stderrdata) . communicate()返回一个元组(stdoutdata, stderrdata)

That matches up with the tuple you got back: 这与你回来的元组匹配:

(b'713b2a82dc713ef273502c00787f9417\n', None)

To access just the standard output ( stdoutdata ), you want element 0 of that tuple: 要仅访问标准输出( stdoutdata ),您需要该元组的元素0

print(event.communicate()[0])

This would do the trick: 这样可以解决问题:

>>> p=Popen('echo -n \x61 |md5sum',shell=True,stdout=PIPE)
>>> p.communicate()
(b'0cc175b9c0f1b6a831c399e269772661  -\n', None)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM