我需要将从 Python 调用的 PowerShell stdout 解码为 Python 字符串。
\n\n我的最终目标是以字符串列表的形式获取 Windows 上网络适配器的名称。我当前的函数如下所示,并且在使用英语的 Windows 10 上运行良好:
\n\ndef get_interfaces():\n ps = subprocess.Popen(['powershell', 'Get-NetAdapter', '|', 'select Name', '|', 'fl'], stdout = subprocess.PIPE)\n stdout, stdin = ps.communicate(timeout = 10)\n interfaces = []\n for i in stdout.split(b'\\r\\n'):\n if not i.strip():\n continue\n if i.find(b':')<0:\n continue\n name, value = [ j.strip() for j in i.split(b':') ]\n if name == b'Name':\n interfaces.append(value.decode('ascii')) # This fails for other users\n return interfaces\nRun Code Online (Sandbox Code Playgroud)\n\n其他用户使用不同的语言,因此value.decode('ascii')其中一些用户会失败。例如,一位用户报告说更改为decode('ISO 8859-2')对他来说效果很好(因此它不是 …
我正在使用 Python 3.6 并且我有一个字节图像:
img = b'\xff\xd8\xff\xe0\x00\x10JFIF\x00'
Run Code Online (Sandbox Code Playgroud)
我需要将字节转换为字符串而不进行编码,因此它看起来像:
raw_img = '\xff\xd8\xff\xe0\x00\x10JFIF\x00'
Run Code Online (Sandbox Code Playgroud)
目标是将其合并到 html 图像标签中:
<img src="'data:image/png;base64," + base64.b64encode(raw_img) + "' />"
Run Code Online (Sandbox Code Playgroud) 关于Python2中unicode的问题。
据我所知,我应该始终decode从外部(文件,网络)读取所有内容。decode使用参数中指定的字符集将外部字节转换为内部 Python 字符串。因此decode("utf8")意味着外部字节是 unicode 字符串,它们将被解码为 python 字符串。
而且我应该总是把encode我写的所有东西都写到外面。我在encode函数参数中指定编码,并将其转换为正确的编码并写入。
这些说法是对的,不是吗?
但有时当我解析 html 文档时,我会遇到解码错误。据我了解其他编码(例如cp1252)的文档,当我尝试使用 utf8 编码对其进行解码时会发生错误。那么问题来了,如何编写防弹应用程序呢?
我发现有一个很好的库来猜测编码是chardet,这是编写防弹应用程序的唯一方法。正确的?
我正在尝试使用Python 3.4.0的pexpect模块(版本3.3).我收到一个错误
TypeError:必须是str,而不是字节
当我调用child.expect方法时.
实际代码是pexpect文档的标准示例:
child = pexpect.spawn('ssh foo@bar.com')
index = child.expect([pexpect.TIMEOUT, pexpect.EOF, ssh_newkey, '.*password:'])
Run Code Online (Sandbox Code Playgroud)
完全相同的代码适用于pexpect模块(版本3.1)和Python版本2.7.6.
GitHub上的Pexpect文档指出,pexpect版本3.3需要Python 2.6或3.2或更高版本.有没有人知道pexpect是否因为某些原因而无法使用Python 3,尽管该模块的文档中有说明?
这是我获得的回溯输出:
Traceback (most recent call last):
File "/home/sambo9/python/python3-pexpect.py", line 17, in <module>
main()
File "/home/sambo9/python/python3-pexpect.py", line 13, in main
child.expect('.*password:')
File "/usr/local/lib/python3.4/dist-packages/pexpect/__init__.py", line 1451, in expect
timeout, searchwindowsize)
File "/usr/local/lib/python3.4/dist-packages/pexpect/__init__.py", line 1466, in expect_list
timeout, searchwindowsize)
File "/usr/local/lib/python3.4/dist-packages/pexpect/__init__.py", line 1535, in expect_loop
c = self.read_nonblocking(self.maxread, timeout)
File "/usr/local/lib/python3.4/dist-packages/pexpect/__init__.py", line 985, in read_nonblocking
self._log(s, 'read')
File "/usr/local/lib/python3.4/dist-packages/pexpect/__init__.py", line 908, in _log
second_log.write(s) …Run Code Online (Sandbox Code Playgroud) 我正在使用Requests模块进行授权,然后从Web API中提取csv内容,并使其在Python 2.7中正常运行。我现在想在Python 3.5中编写相同的脚本,但是遇到一些问题:
"iterator should return strings, not bytes (did you open the file in text mode?)"
Run Code Online (Sandbox Code Playgroud)
在requests.get移动到Python 3.x的时候似乎返回字节,而不是一个字符串,它似乎与看到的编码问题 错误从第三行的第三行引发next(reader)。在Python 2.7中,这不是问题,因为csv函数是在'wb'模式下处理的。
本文非常相似,但是由于我没有直接打开csv文件,因此我似乎无法强制以这种方式编码响应文本: csv.Error:迭代器应返回字符串,而不是字节
countries = ['UK','US','CA']
datelist = [1,2,3,4]
baseurl = 'https://somewebsite.com/exporttoCSV.php'
#--- For all date/cc combinations
for cc in countries:
for d in datelist:
#---Build API String with variables
url = (baseurl + '?data=chart&output=csv' +
'&dataset=' + d +
'&cc=' + cc)
#---Run API Call and create reader object
r = requests.get(url, …Run Code Online (Sandbox Code Playgroud) 如何通过将数字分成连续的字节来轻松地将数字(例如0x616263,6382179以 10 为基数)转换为字符串?所以上面的例子应该转换成'abc'.
我已经尝试过Array.pack但无法弄清楚如何让它转换数字中的多个字节,例如[0x616263].pack("C*")returns 'c'。我也尝试过0x616263.to_s(256),但这会引发 ArgumentError: invalid radix. 我想它需要某种编码信息?
(注意:pack 中的其他数据类型类似于N我上面给出的示例,但只是因为它适合 4 个字节,所以例如[0x616263646566].pack("N")给出cdef,而不是abcdef)
这个问题有点类似于这个问题和这个问题,但又不完全一样。另外,我还想出了如何使用 来从字符串中获取十六进制表示字符串"abcde".unpack("c*").map{|c| c.to_s(16)}.join(""),它给出了'6162636465'。我基本上想倒退。
我不认为这是一个XY 问题,但如果是的话 - 我正在尝试将用 RSA 解码的数字转换为字符串。
谢谢你的帮助。我对 Ruby 不太有经验。我也对 Python 解决方案感兴趣(为了好玩),但我不知道为这个问题添加两种单独的编程语言的标签是否正确。
例如给定任意字符串。可能是chars或只是随机的bytes:
string = '\xf0\x9f\xa4\xb1'
Run Code Online (Sandbox Code Playgroud)
我想输出:
b'\xf0\x9f\xa4\xb1'
Run Code Online (Sandbox Code Playgroud)
这看起来很简单,但我无法在任何地方找到答案。当然,只需键入b后面的字符串即可。但我想在运行时执行此操作,或者从包含字节字符串的变量执行此操作。
如果给定的string是AAAA或一些已知的,characters我可以简单地执行string.encode('utf-8'),但我期望字节串只是随机的。对'\xf0\x9f\xa4\xb1'(随机字节)执行此操作会产生意外结果b'\xc3\xb0\xc2\x9f\xc2\xa4\xc2\xb1'。
一定有更简单的方法来做到这一点吗?
编辑:
我想将字符串转换为字节而不使用编码
我需要将字节数组转换为字符串以发送到 SPI 设备。
有没有更有效的方法来做到这一点?
def writebytes(bytes):
str = ""
for i in bytes: str += chr(i)
self.spi.transfer(str)
Run Code Online (Sandbox Code Playgroud) 我正在使用一些CHIP(Think Raspberry Pi)进行项目开发,我需要将一些信息从从机无线发送回主板。我使用Paho作为我的Mqtt客户,并使用Mosquitto作为我的经纪人。我的问题是,当我按下连接到从属板上的按钮之一时,它将发送我的消息,但是当主板接收到它时,似乎是以“ b”形式接收消息。例如,如果我发送消息“ off”,则当我打印出msg.payload时,它会打印“ b'off'”。这引起了一个问题,因为这样我就无法比较消息以执行我的主板上的命令。
这是我的从板代码:
import paho.mqtt.client as paho
import CHIP_IO.GPIO as GPIO
import time
GPIO.cleanup()
GPIO.setup("XIO-P0", GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup("XIO-P2", GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
client = paho.Client()
client.connect("172.20.0.1", 1883)
print ("CONNECTED")
while True:
if (GPIO.input("XIO-P0") == False):
print ("Button P0 Pressed")
client.publish('tipup', 'flag')
time.sleep(1)
if (GPIO.input("XIO-P2") == False):
print ("Button P2 Pressed")
client.publish('tipup', 'off')
time.sleep(1)
Run Code Online (Sandbox Code Playgroud)
这是我的主板代码(经纪人)
import paho.mqtt.client as paho
import CHIP_IO.GPIO as GPIO
GPIO.cleanup()
GPIO.setup("XIO-P2", GPIO.OUT)
GPIO.output("XIO-P2", GPIO.HIGH)
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + …Run Code Online (Sandbox Code Playgroud) 我想在 python 中打印 Pi 的操作系统系统信息。操作系统命令“cat /etc/os-release”在具有良好行格式的终端中运行良好。
在 Python 中,我使用了:
import subprocess
output = subprocess.check_output("cat /etc/os-release", shell=True)
print("Version info: ",output)
Run Code Online (Sandbox Code Playgroud)
这有效,但我没有得到任何换行符:
Version info: b'PRETTY_NAME="Raspbian GNU/Linux 9 (stretch)"\nNAME="Raspbian GNU/Linux"\nVERSION_ID="9"\nVERSION="9 (stretch)"\nID=raspbian\nID_LIKE=debian\nHOME_URL="http://www.raspbian.org/"\nSUPPORT_URL="http://www.raspbian.org/RaspbianForums"\nBUG_REPORT_URL="http://www.raspbian.org/RaspbianBugs"\n'
Run Code Online (Sandbox Code Playgroud)
如何格式化输出以添加换行符?