2013-01-05 23 views
0

我一定是做錯了。Python變量與編碼sendall()

s.sendall((str("mkd /" + folder.decode() + "/New Folder/ \r\n")).encode()) 

有沒有更好的方法來寫這個?

+0

sendall是否返回字符串? – Hussain

+0

是的,但蟒蛇3要求一個字節字符串 – mb0742

回答

1
s.sendall(b"mkd '/" + folder + b"/New Folder/'\r\n") 

下面是一個使用shlex.quote()在Python 3.3(pipes.quote()在老的Python版本),更強大的版本:

cmd = "mkd {}".format(shlex.quote(posixpath.join(folder, "New Folder"))) 
s.sendall(cmd.encode() + b"\r\n") # send as utf-8 

後者假定folder是Unicode字符串。如果folder是一個字節對象,那麼您不應該盲目地使用folder.decode(),因爲不能保證folder被編碼爲utf-8。 os.fsdecode()是否可用於解碼它取決於folder來自哪裏。

+0

明智的只是在第二個連接的字符串前添加b。你是冠軍! – mb0742