向程序发送字符串

Sending a string to a program

我正在尝试将字符串从 程序 1 发送到另一个程序 程序 2,都在 python 3
例如

#_____________________________________1.py
a = input('Type in a string: ')
#                                     send somehow a string a from this program
#                                     to the second program

我想以某种方式将字符串 a 发送到我的第二个程序,以便它打印出 a:

#_____________________________________2.py
#                                     receive somehow a string from the first
#                                     program and store it in a
print(a)

我该怎么做?

我仍然是一个初级程序员,如果你能帮助我,我会很高兴。

  1. 我需要能够在 1.py
  2. 中输入字符串
  3. 然后我需要能够访问我从 2.py 输入的字符串。
  4. 我必须将它们作为两个单独的文件。

答案:

我找到了解决这个问题的方法。

import subprocess
username = input()
subprocess.Popen(['python.exe', 'file.py', username])
# file_1.py
def get_input():
    return input('Type in a string: ')

# file_2.py
from file_1 import get_input

print(get_input())

两个程序最常见的通信方式是通过 http、tcp 或其他协议。与您的浏览器(一个程序)与网络服务器(另一个程序)通信的方式相同。

您可以从一个程序发送 http 请求,而第二个程序必须侦听该请求。

如果需要更多信息,请查找 SOA。比那个复杂一点,所以有什么问题可以问。

有多种方法可以做到这一点,您可以使用 socketfilepipe, shared-memory, message, ... 将字符串从一个进程传输到另一个进程。

作为使用 messages 的示例,ZeroMQ 提供了一个简单的消息传递库,可以比系统更智能地做到这一点(原始,低级别)套接字:
有关详细信息,请查看 http://zguide.zeromq.org/

HelloWorld 服务器示例:

import time
import zmq

context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://*:5555")

while True:
    #  Wait for next request from client
    message = socket.recv()
    print("Received request: %s" % message)

    #  Do some 'work'
    time.sleep(1)

    #  Send reply back to client
    socket.send(b"World")

HelloWorld 客户端示例:

import zmq

context = zmq.Context()

#  Socket to talk to server
print("Connecting to hello world server…")
socket = context.socket(zmq.REQ)
socket.connect("tcp://localhost:5555")

#  Do 10 requests, waiting each time for a response
for request in range(10):
    print("Sending request %s …" % request)
    socket.send(b"Hello")

    #  Get the reply.
    message = socket.recv()
    print("Received reply %s [ %s ]" % (request, message))

对于文件,您用程序 A 编写一个 文件,然后用程序 B 对其进行轮询。

两个或 N 个 python 程序之间有多种通信方式,例如:

  • Socket
  • 数据库 - MySQL、Mongodb、SQL 服务器...等

或者你可以试试 ZeroMQ

我找到了答案。

import subprocess
username = input()
subprocess.Popen(['python.exe', 'file.py', username], subprocess.creationflags=CREATE_NEW_CONSOLE)