我如何写一个程序,将与我的电脑上的应用程序交互?(即给它输入)



我对python非常陌生,我正在尝试编写一个程序(我将其称为p1),它将生成随机的16位数字,并将它们输入到我计算机上的另一个程序(假设为p2)中。目标是让p1不断向p2输入新数字,直到输入正确的数字。

我知道如何生成数字和什么不是,但我不知道如何使它,所以p1自动输入数字,而不是必须手动进行。基本上我不知道如何让这两个程序相互作用。

如果您想让两个脚本交互,您可以使用subprocess。Popen,更多信息请访问:https://docs.python.org/3/library/subprocess.html。我不确定你所说的程序是什么意思,但是你可以让两个脚本交互的一个例子是:

p1:

import subprocess
import random as r
random_num = int((r.random())*99) # 2 digit number
s = subprocess.Popen(["python", "C:/Users/Jhanz/PycharmProjects/test/p2.py", str(random_num)], stdout=subprocess.PIPE)
while s.stdout.read() != b"Congratulations! You guessed the number!rn":
random_num = int((r.random()) * 99)
s = subprocess.Popen(["python", "C:/Users/Jhanz/PycharmProjects/test/p2.py", str(random_num)],
stdout=subprocess.PIPE)
print("You guessed the number!", random_num)

p2:

import sys
number_to_guess = 10
if int(sys.argv[1]) == number_to_guess:
print("Congratulations! You guessed the number!")
else:
print("You didn't guess the number!")

最新更新