【问题标题】:how to send a string between two python programs [closed]如何在两个python程序之间发送字符串[关闭]
【发布时间】:2022-06-14 10:21:04
【问题描述】:

我正在制作的项目需要这个,但我不知道该怎么做。

我正在寻找如下语法:
发件人.py

string = "Hello"
send(hello)

阅读器.py

string = read()
print(string)

编辑
提出了解决方案。
https://github.com/Ccode-lang/simpmsg

【问题讨论】:

  • 你看过import吗?
  • 如果它们实际上是两个不同的程序,而不仅仅是同一个程序的不同模块,那么也许看看pipes
  • 我看过导入。它似乎不适用于我的情况。我需要多个发件人程序。我想过也许使用 tcp 但这没有用。我现在正在研究管道。
  • 欢迎来到 Stack Overflow!请拨打tour。你到底想完成什么?如果你想从 Python 文件中获取字符串,你可以导入它。如果您希望将字符串从一个 Python 程序发送到另一个程序,那么存在一个问题:Interprocess communication in Python(尽管我自己没有这方面的经验)。请edit 澄清。有关更多提示,请参阅How to Ask。
  • 也许只是将字符串写入文件,然后让其他程序从同一个文件中读取?

标签: python networking tcp


【解决方案1】:

如果两个程序员在不同的计算机上,你可以尝试使用套接字

server.py

import socket

s = socket.socket()
port = 12345
s.bind(('', port))
s.listen(5)
c, addr = s.accept()
print "Socket Up and running with a connection from",addr
while True:
    rcvdData = c.recv(1024).decode()
    print "S:",rcvdData
    sendData = raw_input("N: ")
    c.send(sendData.encode())
    if(sendData == "Bye" or sendData == "bye"):
        break
c.close()

client.py

import socket

s = socket.socket()
s.connect(('127.0.0.1',12345))
while True:
    str = raw_input("S: ")
    s.send(str.encode());
    if(str == "Bye" or str == "bye"):
        break
    print "N:",s.recv(1024).decode()
s.close()

如果您想先存储它,以便其他程序员下次可以阅读它 使用文件

发件人.py

file1 = open("myfile.txt","w")
file1.write("hello")
file1.close()
  

reader.py

file1 = open("myfile.txt","r")
data = file1.read()
file1.close()
print(data)
  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 2014-02-26
    • 1970-01-01
    • 2018-03-25
    • 2014-01-14
    • 2019-08-11
    • 1970-01-01
    相关资源
    最近更新 更多