|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
有一个猜数程序:
import random
num = random.randint(1, 100)
count = 0
while True:
ans = int(input("Please input a number between 1 and 100:"))
count += 1
if ans == num:
print(f"The number is {ans}!")
break
elif ans > num:
print("Too Large!")
continue
else:
print("Too Small!")
continue
现在使用subprocess模块,运行该程序进行自动猜数。
import subprocess
import shlex
process = subprocess.Popen(shlex.split('python ask.py'), stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
process.stdin.write(b"50")
process.stdin.close()
print(process.stdout.read().decode())
如何才能多次进行猜想,并输出结果呢?,使用stdin.write()和stdout.read(),好像只能进行一次输出输出过程。在没有进行stdin.close(),没法进行stdout.read(),就没法多次输出猜想过程。
我在网上找的了stdout.read1()方法可以输出当前stdout结果,写出下面程序可以自动猜想,但是stdout.read1()好像不是subprocess的方法,在Pycharm里面会有黄色警告。
import subprocess
import shlex
low = 1
high = 100
mid = (low + high) // 2
process = subprocess.Popen(shlex.split('python ask.py'), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
print(process.stdout.read1().decode())
process.stdin.write(f'{mid}\n'.encode())
print(f"{mid}")
process.stdin.flush()
while True:
hint = process.stdout.read1().decode()
print(hint)
if "Too Small" in hint:
low = mid + 1
mid = (low + high) // 2
elif "Too Large" in hint:
high = mid - 1
mid = (low + high) // 2
else:
print(process.stdout.read1().decode())
break
process.stdin.write(f'{mid}\n'.encode())
print(process.stdout.read1().decode())
process.stdin.flush()
print(f"{mid}") |
|