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

python运行bash命令得到错误结果,python,bash,cmd,Python,Bash,Cmd,嗨,我正在尝试在Python3.2上运行这个bash cmd。以下是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()) 这给了我下

嗨,我正在尝试在Python3.2上运行这个bash cmd。以下是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())
这给了我下一个结果:
echo-n-e'\x61'| md5
(b'713b2a82dc713ef273502c00787f9417\n',无)

但是当我在bash中运行这个打印的cmd时,我得到了不同的结果:
0cc175b9c0f1b6a831c399e269772661

我哪里出错了?

来自:

communicate()
返回一个元组
(stdoutdata,stderdata)

与你得到的元组匹配:

(b'713b2a82dc713ef273502c00787f9417\n', None)
要仅访问标准输出(
stdoutdata
),需要该元组的元素
0

print(event.communicate()[0])

这个问题的关键在于你说:

但是当我在bash中运行这个打印的cmd时

子流程模块的
Popen
函数不一定使用bash,它可能使用一些其他shell,例如
/bin/sh
,这些shell不一定会以与bash相同的方式处理
echo
命令。在我的系统上,在bash中运行命令会产生与您得到的结果相同的结果:

$ echo -n -e '\x61' | md5sum
0cc175b9c0f1b6a831c399e269772661  -
但是如果我在
/bin/sh
中运行命令,我会得到:

$ echo -n -e '\x61' | md5sum
20b5b5ca564e98e1fadc00ebdc82ed63  -
这是因为我的系统上的
/bin/sh
不理解
-e
选项,也不理解
\x
转义序列

如果我用python运行您的代码,我会得到与使用
/bin/sh
相同的结果:

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

这将实现以下目的:

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

您不需要使用echo来传递数据。您可以直接使用python进行此操作,即:

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

奇怪的是,它在python 2.5中适用(即返回0cc175b9c0f1b6a831c399e269772661),但如果您真正需要的是MD5哈希,只需使用hashlib模块(及其MD5函数)。