import socket, sys host='?' port=3306 s= socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: s.connect((host,port)) except socket.gaierror, e: print "Address-related error connecting to server: %s" % e sys.exit(1) except socket.error, e: print "Connection error: %s" % e sys.exit(1) while True: try: data = raw_input("I say: ") s.send(data) buf = s.recv(1024) if len(buf): print "He says: " + buf except: print "Dialogue Over" s.close() sys.exit(0)关于这个代码,pycharm报错 except socket.gaierror,e: ^ SyntaxError: invalid syntax
时间: 2023-12-17 07:03:00 浏览: 121
这个代码是 Python 2.x 的代码,在 Python 3.x 中会出现语法错误。可以将 except socket.gaierror, e: 改为 except socket.gaierror as e:。同时,raw_input() 也应该改为 input()。修改后的代码如下:
```python
import socket
import sys
host = '?'
port = 3306
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((host, port))
except socket.gaierror as e:
print("Address-related error connecting to server: %s" % e)
sys.exit(1)
except socket.error as e:
print("Connection error: %s" % e)
sys.exit(1)
while True:
try:
data = input("I say: ")
s.send(data.encode())
buf = s.recv(1024)
if len(buf):
print("He says: " + buf.decode())
except:
print("Dialogue Over")
s.close()
sys.exit(0)
```
请注意,此代码仅用于参考,因为 host 和 port 都是未知的,所以代码可能无法正常工作。
阅读全文