在python程序之间发送字符串

在python程序之间发送字符串,python,python-3.x,sockets,Python,Python 3.x,Sockets,我想在两个Python程序之间发送一些简单的信息,比如int或字符串。我想通过让程序从一行文件读写来实现这一点。但这似乎不起作用,因为一个文件似乎阻止了该文件。特别是因为我想每隔1/12秒左右检查一次更新 如果它真的起作用,我的想法是使用一个程序发送消息 with open('input.py','w') as file: file.write('hello') 并随信接受 with open('input.py','r') as file: print(file.read()

我想在两个Python程序之间发送一些简单的信息,比如int或字符串。我想通过让程序从一行文件读写来实现这一点。但这似乎不起作用,因为一个文件似乎阻止了该文件。特别是因为我想每隔1/12秒左右检查一次更新

如果它真的起作用,我的想法是使用一个程序发送消息

with open('input.py','w') as file:
    file.write('hello')
并随信接受

with open('input.py','r') as file:
    print(file.read())

我一直在研究如何使用套接字,但每个“简单”教程似乎都针对一些更复杂的用例。那么,我如何以实际可行的方式完成我需要做的事情呢?

最好的方法是使用
socket
库。这将创建一个客户机-服务器连接,从那里可以在程序之间发送字符串

server.py:

import socket                

s = socket.socket()          
print "Socket successfully created"
port = 12345     # Reserve a port on your computer...in our case it is 12345, but it can be anything
s.bind(('', port))         
print "Socket binded to %s" %(port) 
s.listen(5)    # Put the socket into listening mode       
print "Socket is listening"            

while True:
  c, addr = s.accept()   # Establish connection with client
  print 'Got connection from', addr 
  c.send('Thank you for connecting')   # Send a message to the client
  c.close()
# start the server:
$ python server.py
Socket successfully created
Socket binded to 12345
Socket is listening
Got connection from ('127.0.0.1', 52617)

# start the client:
$ python client.py
Thank you for connecting
客户端.py

import socket                

s = socket.socket()
port = 12345     # Define the port on which you want to connect
s.connect(('127.0.0.1', port))   # Connect to the server on local computer
print s.recv(1024)   # Receive data from the server 
s.close()
从终端/外壳:

import socket                

s = socket.socket()          
print "Socket successfully created"
port = 12345     # Reserve a port on your computer...in our case it is 12345, but it can be anything
s.bind(('', port))         
print "Socket binded to %s" %(port) 
s.listen(5)    # Put the socket into listening mode       
print "Socket is listening"            

while True:
  c, addr = s.accept()   # Establish connection with client
  print 'Got connection from', addr 
  c.send('Thank you for connecting')   # Send a message to the client
  c.close()
# start the server:
$ python server.py
Socket successfully created
Socket binded to 12345
Socket is listening
Got connection from ('127.0.0.1', 52617)

# start the client:
$ python client.py
Thank you for connecting

如您所见,由于
socket
库中的
send()
recv()
方法,客户端能够通过服务器接收字符串“感谢您的连接”。

您的问题太广泛了,sockets可能是一种解决方法,请查看pyzmq或tornado或类似的库,它们允许您通过sockets实现异步通信。您的示例不起作用的主要原因是您试图写入以只读模式打开的文件,反之亦然。