我正在使用此代码从外部程序获取标准输出:
>>> from subprocess import *
>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
Run Code Online (Sandbox Code Playgroud)
communic()方法返回一个字节数组:
>>> command_stdout
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n'
Run Code Online (Sandbox Code Playgroud)
但是,我想将输出作为普通的Python字符串.所以我可以这样打印:
>>> print(command_stdout)
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2
Run Code Online (Sandbox Code Playgroud)
我认为这是binascii.b2a_qp()方法的用途,但是当我尝试它时,我又得到了相同的字节数组:
>>> binascii.b2a_qp(command_stdout)
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n'
Run Code Online (Sandbox Code Playgroud)
有人知道如何将字节值转换回字符串吗?我的意思是,使用"电池"而不是手动操作.而且我希望它能用于Python 3.
我想在python3中生成一个16字节长的随机字符串用于加密目的(AES加密)。urandom(n)似乎是获得真正随机字符的方法:
os.urandom(n):
返回适合加密使用的 n 个随机字节字符串。
由于我需要一个 16 字节的随机字符串,我认为这对我有用:编辑我现在包含了一个更复杂的示例,演示了我遇到的问题。
from os import urandom
from Crypto.Cipher import AES
from base64 import b64encode
import sys
rnd=urandom(16)
rnd_bytes=b64encode(rnd).decode('utf-8')
print(sys.getsizeof(rnd_bytes))
print(len(rnd_bytes))
print(type(rnd_bytes))
AESencrypter=AES.new('my key',AES.MODE_CBC,rnd_bytes)
Run Code Online (Sandbox Code Playgroud)
注意:我使用此答案将 urandom字节转换为string。输出是:
73
24
文件“/User/test.py”,第 14 行,在 AESencrypter=AES.new('my kes',AES.MODE_CBC,rnd_bytes) 文件“/Library/Frameworks/Python.framework/Versions/3.6/lib/python3. 6/site-packages/Crypto/Cipher/AES.py", line 95, in new return AESCipher(key, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3 .6/site-packages/Crypto/Cipher/AES.py”,第 59 行,在init blockalgo.BlockAlgo 中。init (self, _AES, key, *args, **kwargs) 文件“/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Crypto/Cipher/blockalgo.py”,行141、在init self._cipher = factory.new(key, *args, …