python - 在 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())
我一直在研究如何使用套接字来做到这一点,但每个“简单”教程似乎都针对一些更复杂的用例。那么我该如何以一种实际可行的方式做我需要做的事情呢?
解决方案
最好的路线是使用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
。
推荐阅读
- javascript - 未指定表的 SELECT * 无效
- java - 如何对具有覆盖率的 void 函数执行单元测试
- reactjs - 如何修复 create-react-app 中未找到的 404
- mule - 数据转json
- sql - OVER partition BY 没有给出正确的结果
- matlab - 在 EEGLAB 中加载 .bdf 文件
- python - 通过左连接 SQL 和 Pandas 合并数据框
- android - 电话号码和电子邮件验证都可以在 Firebase 中应用吗?
- python - 将价格绘制为非零交易量值的水平线
- javascript - Azure Function - js - 运行不正确,但日志中没有错误