I write a socket server programmer:
#-*- coding:utf-8 -*-
# Author:sele
import socket
HOST = '127.0.0.1'
PORT = 65432
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
when I run it in my command, there gets error:
sele-MacBook-Pro:test01 ldl$ ./tests02-server.py
./tests02-server.py: line 5: import: command not found
;; connection timed out; no servers could be reached
Error: Current platform "darwin 18" does not match expected platform "darwin 16"
Error: If you upgraded your OS, please follow the migration instructions: https://trac.macports.org/wiki/Migration
OS platform mismatch
while executing
"mportinit ui_options global_options global_variations"
Error: /opt/local/bin/PORT: Failed to initialize MacPorts, OS platform mismatch
./tests02-server.py: line 10: syntax error near unexpected token('
./tests02-server.py: line 10:('
./tests02-server.py: line 10:('
with socket.socket(socket.AF_INET,
./tests02-server.py: line 10:
socket.SOCK_STREAM) as s:'
why there can not find the import
?
EDIT-01
I inserted this line to my first line.
#!/usr/bin/env python
when I run the script, there gets this error:
sele-MacBook-Pro:test01 ldl$ ./tests02-server.py
Traceback (most recent call last):
File "./tests02-server.py", line 11, in <module>
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
AttributeError: __exit__
aircrafts-MacBook-Pro:test01 ldl$ ./tests02-server.py
Traceback (most recent call last):
File "./tests02-server.py", line 11, in <module>
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
AttributeError: __exit__
You're running your program as a shell script, not a python program. Add an appropriate #!
line:
#!/usr/bin/env python
to the top of your program, or run it explicitly from the command line:
$ python tests02-server.py
The answer to your new question is that you can't use socket.socket(socket.AF_INET, socket.SOCK_STREAM)
with with
. So that a with
statement can clean up the resource it is working with, that resource's object has to have an __exit__
method. What socket.socket(socket.AF_INET, socket.SOCK_STREAM)
returns obviously has no __exit__
method for with
to call, hence this error.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.