【发布时间】:2014-07-22 02:47:46
【问题描述】:
如果有人可以帮助我,那就太好了。我在 Linux 上使用 python 2.6 版创建了一个 python 服务器和客户端脚本。据我了解,只要我在 Windows 中安装相同版本的 python,我应该能够毫无问题地运行相同的脚本。我这样做了,脚本除了打印出“Importerror:没有名为 fcntl 的模块”之外什么也没做。我正在添加服务器代码和客户端。如果有人能阐明我做错了什么,那就太好了。同样,既然我已经在这里了,我怎么可能让客户端代码在 Windows 中自动运行,而不必在客户端机器上安装 python。
客户
#!/usr/bin/env python
import socket
import fcntl
import struct
#############################
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
def getHwAddr(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', ifname[:15]))
return ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1]
host = socket.gethostname()
#print host
#print getHwAddr('eth0')
#print get_ip_address(enter code here'eth0')
info = "<"+get_ip_address('eth0')+">","{"+ getHwAddr('eth0')+"}","~"+host+"~"
############################
TCP_IP = 'IP'
TCP_PORT = xxxx
BUFFER_SIZE = 1024
MESSAGE = "Hello, World!"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(str(info))
data = s.recv(BUFFER_SIZE)
s.close()
#print "received data:", data
服务器
import socket
import re
import subprocess
TCP_IP = ''
TCP_PORT = XXXX
BUFFER_SIZE = 2048 # Normally 1024, but we want fast response
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(50)
conn, addr = s.accept()
print 'Connection address:', addr
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
print "received data:", data
da = open("data.txt", "wb")
da.write(data);
conn.send(data) # echo
subprocess.Popen(["python", "ReadandInsert.py"])
conn.close()
另外,快速提及。服务器端代码将仅在 Linux 中运行,客户端代码将在 Windows 中运行。再次感谢任何可以伸出援手的人...!!
【问题讨论】:
-
如果你注意到fcntl documentation,它只适用于Unix。虽然 python 可以在许多不同的平台上工作,但标准库中的各种模块(甚至模块中的函数/类)依赖于操作系统特定的行为,并且仅在操作系统支持该功能时才提供。
标签: python linux windows scripting