python32版本,出现问题“struct.error: argument for 's' must be a bytes object”的解决办法


@for ever 2012-06-25


在python32版本下面,下面的代码:


msg = pack(">H%ds" % len(reason), code, reason)

执行后出现如下的错误:

struct.error: argument for 's' must be a bytes object

做如下修改,错误解决:

msg = pack(">H%ds" % len(reason), code, reason.encode('utf-8'))

关于struct.pack函数,参数个数是无限的。第一个参数定义打包格式,
剩余的所有参数都是要打包的内容。
第一个格式参数具体写法如下:
Format c Type Python Note
x pad byte no value  
c char string of length 1  
b signedchar integer  
B unsignedchar integer  
? _Bool bool (1)
h short integer  
H unsignedshort integer  
i int integer  
I unsignedint integer or long  
l long integer  
L unsignedlong long  
q longlong long (2)
Q unsignedlonglong long (2)
f float float  
d double float  
s char[] string  
p char[] string  
P void* long  
此外,还包含相应的大/小端设置(如果忽略该设置,默认<):
@ native native
= native standard
< little-endian standard
> big-endian standard
! network (= big-endian) standard



@forandever 2012-6-25






                                    
发布了111 篇原创文章 · 获赞 20 · 访问量 83万+
展开阅读全文

python实现opencv报错an integer is required

07-11

以下是代码 managers.py ``` #!/usr/bin/env python # -*- coding: utf-8 -*- import cv2 import numpy import time '''     视频管理 ''' class CaptureManager(object): def __init__(self,capture,previewWindowManager = None,shouldMirrorPreview = False): self.previewWindowManager = previewWindowManager self.shouldMirrorPreview = shouldMirrorPreview #定义非公有变量,单下划线开始,为保护变量,只有类对象或子类对象可以访问 protected #如果以双下划线开始,为私有成员变量,只有类对象自已可以访问,像private self._capture = capture self._channel = 0 self._enteredFrame = False self._frame = None self._imageFilename = None self._videoFilename = None self._videoEncoding = None self._videoWriter = None self._startTime = None self._framesElapsed = long(0) self._fpsEstimate = None @property def channel(self): return self._channel @channel.setter def channel(self,value): if self._channel != value: self._channel = value self.frame = None @property def frame(self): if self._enteredFrame and self._frame is None: _,self._frame = self._capture.retrieve() return self._frame @property def isWritingImage(self): return self._imageFilename is not None @property def isWritingVideo(self): return self._videoFilename is not None #只能同步一帧 def enterFrame(self): """Capture the next frame,if any.""" if self._capture is not None: #but first,check that any previous frame was exited. #assert not self._enteredFrame,'previous enterFrame() had no matching exitFrame()' if self._capture is not None: self._enteredFrame = self._capture.grab() else: None def exitFrame(self): """可以从当前通道中取得图像,估计帧率,显示图像,执行暂停的请求,向文件中写入图像""" #计算帧率 if self.frame is None: self._enteredFrame = False return #Update the FPS estimate and related variables.通过窗体显示图像 if self._framesElapsed == 0: self._startTime = time.time() else: timeElapsed = time.time() - self._startTime self._fpsEstimate = self._framesElapsed/timeElapsed self._framesElapsed += 1 #Draw to the Window,if any.保存图像文件 if self.previewWindowManager is not None: if self.shouldMirrorPreview: mirroredFrame = numpy.fliplr(self._frame).copy() self.previewWindowManager.show(mirroredFrame) else: self.previewWindowManager.show(self._frame) #Write to the image file,if any.保存图像文件 if self.isWritingImage: cv2.imwrite(self._imageFilename,self._frame) self._imageFilename = None #Write to the video file,if any.保存视频文件 self._writeVideoFrame() #Release the frame.释放资源 self._frame = None self.enteredFrame = False def writeImage(self,filename): """Write the next exited frame to an image file."""#保存图片,公有函数 self._imageFilename = filename def startWritingVideo(self,filename,encoding = cv2.VideoWriter_fourcc('I','4','2','0')): """Start writing exited frames to a video file."""#开始保存视频,公有函数 self._videoFilename = filename self._videoEnchding = None self._videoWriter = None def _writeVideoFrame(self):#停止视频写入,公有函数 if not self.isWritingVideo: return if self._videoWriter is None: fps = self._capture.get(cv2.CAP_PROP_FPS) if fps == 0.0: #The capture's FPS is unknown so use an entimate. if self._framesElapsed < 20: #Wait until more frames frames elapse so that the estimate is more stable. return else: fps = self._fpsEstimate size = (int(self._capture.get(cv2.CAP_PROP_FRAME_WIDTH)),\ int(self._capture.get(cv2.CAP_PROP_FRAME_HEIGHT))) self._videoWriter = cv2.VideoWriter(self._videoFilename,self._videoEncoding,fps,size) self._videoWriter.write(self._frame) '''     窗口管理,支持键盘事件 ''' class WindowManager(object): def __init__(self,windowName,keypressCallback = None): #窗体名称#按键回调函数 self.keypressCallback = keypressCallback self._windowName = windowName self._isWindowCreated = False @property def isWindowCreated(self):#检查窗体是否被创建 return self._isWindowCreated def creatWindow(self):#创建窗体 cv2.namedWindow(self._windowName) self._isWindowCreated = True def show(self,frame):#显示图像 cv2.imshow(self._windowName,frame) def destroyWindow(self):#关闭窗体释放资源 cv2.destroyWindow(self._windowName) self._isWindowCreated = False def processEvents(self): keycode = cv2.waitKey(1) if self.keypressCallback is not None and keycode != -1: #Discard any non-ASCII info encoded by GTY. keycode &= 0xFF self.keypressCallback(keycode) ``` cameo.py ``` #!/usr/bin/env python # -*- coding: utf-8 -*- import cv2 from managers import WindowManager,CaptureManager class Cameo(object): def __init__(self): self._windowManager = WindowManager('Cameo',self.onKeypress) self._captureManager = CaptureManager(cv2.VideoCapture(0),self._windowManager,True) def run(self): """Run the main loop.""" self._windowManager.creatWindow() while self._windowManager.isWindowCreated: self._captureManager.enterFrame() frame = self._captureManager.frame #TODO:Filter the frame (Chapter 3). self._captureManager.exitFrame() self._windowManager.processEvents() def onKeypress(self,keycode): """Handle a keycode. space -> 载图 tab -> 启动和停止视频录制 escape -> 退出应用 """ if keycode == 32: #space self._captureManager.writeImage('screenshot.png') elif keycode == 9:#tab if not self._captureManager.isWritingVideo: self._captureManager.startWritingVideo("screencast.avi") else: self._captureManager.stopWritingVideo() elif keycode == 27:#escape self._windowManager.destroyWindow() if __name__ == "__main__": Cameo().run() ``` 问答

TypeError: expected str, bytes or os.PathLike object, not tuple此报错有大神遇到过吗怎么解决

05-23

import gensim import torch from util import read_caption_data, char_table_to_sentence, word2vec from torch.utils.serialization import load_lua import os def save_embeddings(filepath, filename, embeddings): if not os.path.exists(filepath): os.mkdir(filepath) target_path = os.path.join(filepath, filename) torch.save({'embeds': embeddings}, target_path) # 保存整个网络,包括整个计算图 return True class Word_Embeddings(): def __init__(self, root_dir, caption_dir, split_file, alphabet): self.caption_dir = caption_dir self.split_file = split_file self.alphabet = alphabet self.dir_path = os.path.join(root_dir, 'pretrained_embeddings') self.model = gensim.models.KeyedVectors.load_word2vec_format('/data0/Masters/yanwencai/CrossModalRetrieval-master/models/GoogleNews-vectors-negative300.bin', binary=True) #加载Google训练的词向量 def load_caption(self, cap): assert (os.path.isfile(cap)) cls, fn = cap.split('/')[-2], cap.split('/')[-1] file_path = os.path.join((self.dir_path, cls)) #报错行 caption = load_lua(cap) char = caption['char'] sentence = char_table_to_sentence(self.alphabet, char) embeds = word2vec(self.model, sentence, sen_size=16, emb_size=300) return file_path, fn, embeds alphabet = "abcdefghijklmnopqrstuvwxyz0123456789-,;.!?:'\"/\\|_@#$%^&*~`+-=<>()[]{} " data_dir = '/data0/Masters/yanwencai/CrossModalRetrieval-master/datasets/CUB_200_2011/' split_file = os.path.join(data_dir, 'train_val.txt') caption_dir = os.path.join(data_dir, 'cub_icml') caption_list = read_caption_data(caption_dir, split_file) WE = Word_Embeddings(data_dir, caption_dir, split_file, alphabet) for idx, cap in enumerate(caption_list): filepath, fn, embeds = WE.load_caption(cap) #报错行 if save_embeddings(filepath, fn, embeds): print(filepath, fn, 'saved') ``` 错误描述:Traceback (most recent call last): File "word_embeddings.py", line 61, in <module> filepath, fn, embeds,type = WE.load_caption(cap) File "word_embeddings.py", line 36, in load_caption file_path,type = os.path.join((self.dir_path, cls)) File "/home/amax/anaconda2/lib/python3.6/posixpath.py", line 80, in join a = os.fspath(a) TypeError: expected str, bytes or os.PathLike object, not tuple 请各位大神帮忙看一下,xie'xie 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览