如何在python中写整数并读取整数大小

时间:2014-07-15 18:26:12

标签: python

在Python中,如何将整数写入管道并读取为整数大小。

例如如下

下面的代码有一些错误我知道,但它是让你理解我想要的

# variable r and w is pipe descriptor for read and write respectively in thread1 and 2

# thread1
a = 10
w.write(a)     # i know it has an error occur as it requires string as the argument    

# thread2
a = r.read(sys.getsizeof(1))   #read data as much as size of integer
if a == 1:
  #do something
elif a == 10:
  #do something

2 个答案:

答案 0 :(得分:5)

您应该使用struct模块:

>>> import struct
>>> from StringIO import StringIO
>>> c = StringIO()
>>> c.write(struct.pack('I', 100))
>>> c.seek(0)
>>> struct.unpack('I', c.read(4))
(100,)

答案 1 :(得分:1)

假设在这种情况下管道只是在线程之间移动数据的方法,我会在整数之后写一个终止字符,然后在第二个线程中查看它。

#thread 1
a = 10
w.write(str(a))
w.write('#')

#-----------

#thread 2
a = ""
b = r.read(1)
while(b != '#'):
    a = a + b
    b = r.read(1)

if int(a) == 1:
    #do something