首页 > 解决方案 > 在 python 程序之间发送一个字符串

问题描述

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

如果它确实有效,我的想法用例将是一个程序发送一条消息

with open('input.py','w') as file:
    file.write('hello')

并收到它

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

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

标签: pythonpython-3.xsockets

解决方案


最好的路线是使用socket图书馆。这将创建一个客户端-服务器连接,您可以从那里在程序之间发送字符串。

服务器.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()

客户端.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()

从终端/外壳:

# 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

如您所见,由于库中的send()andrecv()方法,客户端能够从服务器接收字符串“Thank you for connection” socket


推荐阅读