TypeError: expected string or Unicode object, NoneType found
两个python脚本,一个是socket服务端,一个是客户端。
使用进程池来多进程运行,报错: multiprocessing.Pool ==> TypeError: expected string or Unicode object, NoneType found
(请无视我的烂代码)
具体代码如下:
- 服务端:
import socketimport multiprocessing
def get_mac(cli, caddr):
while True:
macinfo = cli.recv(1024)
if macinfo:
print('get [{}] from {}'.format(macinfo, caddr))
else:
print('establish but get nothing from {}'.format(caddr))
print('TERMINAL CLI-SOCKET')
cli.close()
cli.sendall('Done')
log.info('Send Confirm <Done> To {}'.format(caddr))
info = macinfo.split(',').strip()
return info
def gen_config(info):
print(info)
def start(func):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
addr = ('mn0', 1995)
sock.bind(addr)
sock.listen(5)
pool = multiprocessing.Pool()
while True:
print('waitting for new connect ...')
cli, caddr = sock.accept()
print('establish new connect with {}'.format(caddr))
pool.apply_async(func, args=(cli, caddr,), callback=gen_config)
pool.close()
pool.join()
if __name__ == '__main__':
start(get_mac)
- 客户端:
#!/usr/bin/env pythonimport socket
def send():
addr = ('mn0', 1995)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(addr)
print('Establish Connect with {}'.format(addr))
sock.sendall('{},{}'.format('192.168.85.1', 'da:ad:as:as:as:sa'))
print('send 192.168.85.1 da:ad:as:as:as:sa')
data = sock.recv(1024)
if data == 'Done':
print('Confirm Send')
sock.close()
if __name__ == '__main__':
send()
回答:
客户端代码
sock.sendall('{},{}'.format('192.168.85.1', 'da:ad:as:as:as:sa'))
改成
b = '{},{}'.format('192.168.85.1', 'da:ad:as:as:as:sa'); sock.sendall(b.encode())
如果查看套接字文档,可以看到sendall需要发送字节。Python有一个内置函数将String转换为字节,称为encode。所以,你必须使用
sock.sendall(message.encode())
将其转换为字节,以便可以发送。
以上是 TypeError: expected string or Unicode object, NoneType found 的全部内容, 来源链接: utcz.com/a/157689.html