Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 套接字服务器中的换行符?_Python_Sockets_Line Breaks - Fatal编程技术网

Python 套接字服务器中的换行符?

Python 套接字服务器中的换行符?,python,sockets,line-breaks,Python,Sockets,Line Breaks,有人能告诉我如何摆脱这个城市的断线吗?每次回显字符串时,其上都有一个换行符。基本上是一个空字符。我怎样才能摆脱它 from socket import * import threading import thread def handler(clientsock,addr): while 1: data = clientsock.recv(BUFSIZ) if not data: break msg = data

有人能告诉我如何摆脱这个城市的断线吗?每次回显字符串时,其上都有一个换行符。基本上是一个空字符。我怎样才能摆脱它

from socket import *
import threading
import thread

def handler(clientsock,addr):
    while 1:
        data = clientsock.recv(BUFSIZ)
        if not data:
            break
        msg = data
        print msg
        clientsock.send(msg)
    clientsock.close()

if __name__=='__main__':
    host = 'localhost'
    port = 20000
    BUFSIZ = 1024
    ADDR = (host, port)
    serversock = socket(AF_INET, SOCK_STREAM)
    serversock.bind(ADDR)
    serversock.listen(2)

print 'Version 0.1','-',host,':',port

while 1:
    clientsock, addr = serversock.accept()
    print 'initiated',addr[0],'on',addr[1]
    thread.start_new_thread(handler, (clientsock, addr))
替换

print msg

显然,
import sys
位于顶部。出现换行符的原因是,为了便于使用,
print
会自动将其添加到每次打印中
sys.stdout.write不执行此操作。

替换

print msg


显然,
import sys
位于顶部。出现换行符的原因是,为了便于使用,
print
会自动将其添加到每次打印中
sys.stdout.write
不能这样做。

@nightcracker已经回答了这个问题,我只想在这里留下另一个可能的解决方案。可以在
print
语句后添加逗号,以禁止在字符串后添加换行符

print msg, # <- notice the comma

print msg,#@nightcracker已经回答了这个问题,我只想在这里留下另一个可能的解决方案。可以在
print
语句后添加逗号,以禁止在字符串后添加换行符

print msg, # <- notice the comma

print msg,#非常有意义。非常感谢。有没有一种方法可以在不使用换行符的情况下重新分配
msg
?另一种方法是在print语句后添加逗号:
print msg,
@Matthew,
msg
实际上没有换行符。它由
print
语句附加。如果它没有重定向到文件,则可以在换行符上刷新
stdout
,例如,如果它不是交互式的:
if getattr(sys.stdout,'isatty',lambda:False)()和any(msg中的n表示b'\r\n'):sys.stdout.flush()
非常有意义。非常感谢。有没有一种方法可以在不使用换行符的情况下重新分配
msg
?另一种方法是在print语句后添加逗号:
print msg,
@Matthew,
msg
实际上没有换行符。它由
print
语句附加。如果它没有重定向到文件管道,也就是说,如果它不是交互式的,则可以在换行符上刷新
stdout
:如果getattr(sys.stdout,'isatty',lambda:False)()和any(msg中的n表示b'\r\n'):sys.stdout.flush()
不使用通配符导入(
*
)除非在REPL.use
.sendall()
中,否则不会发送所有数据。除非在REPL.use
.sendall()
中,否则不要使用通配符导入(
*
),否则不会发送所有数据。@J.F.Sebastian仅在调用
print
之间,AFAIK
print
可能会被多次调用。如果上一次调用没有以换行符结束(softspace为true),则会打印
”,但OP希望清除“空”字符
print s,
仅在调用
print
之间转换为.@J.F.Sebastian,AFAIK
print
可能会被调用多次。如果上一次调用没有以换行符结束(softspace为true),则会打印
”,但OP希望清除“空”字符<代码>打印,
转换为。