【问题标题】:python auto interaction with other programpython自动与其他程序交互
【发布时间】:2020-04-02 14:41:06
【问题描述】:

我有一个这样的脚本:

# coding:utf8
# python2

import random

first_num = str(random.randint(0, 10))
second_num = str(random.randint(0, 10))

first_input = raw_input('input %s: ' % first_num)
second_input = raw_input('input %s: ' % second_num)

if first_num==first_input and second_num==second_input:
    print('Right!')
else:
    print('Wrong!')

如果你必须通过另一个 python 脚本与之交互,你怎么能总是得到“正确!”?

【问题讨论】:

  • 与另一个 python 脚本交互是什么意思?
  • 我可以手动完成。很容易得到“正确!”。但我不知道如何通过另一个 python 脚本来自动化这个过程。

标签: python automation interactive


【解决方案1】:

您可以在之后导入脚本/模块 first_num = str(random.randint(0, 10)) second_num = str(random.randint(0, 10)) 喜欢

first_num = str(random.randint(0, 10))
second_num = str(random.randint(0, 10))
import <yourscript/module>

【讨论】:

  • 假设脚本无法修改,如何解决?
【解决方案2】:

把题改成python3,文件名为want_right.py

# coding:utf8
# python3

import random

first_num = str(random.randint(0, 10))
second_num = str(random.randint(0, 10))

first_input = input('input {}: '.format(first_num))
second_input = input('input {}: '.format(second_num))

if first_num==first_input and second_num==second_input:
    print('Right!')
else:
    print('Wrong!')

我的答案是:

# coding:utf8
# python3

import re
import subprocess


class ProcessInteraction:
    process = None

    def __init__(self, command):
        self.process = subprocess.Popen(
            command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)

    def __del__(self):
        self.process.stdin.close()
        self.process.stdout.close()

    def read_line(self):
        return self.process.stdout.readline().decode('utf8')

    def read_util(self, want_end_str):
        current_str = ''
        while True:
            current_str += self.process.stdout.read(1).decode('utf8')
            if current_str.endswith(want_end_str):
                return current_str

    def read_util_re(self, want_re_str):
        current_str = ''
        while True:
            current_str += self.process.stdout.read(1).decode('utf8')
            s = re.search(want_re_str, current_str)
            if s:
                return [current_str, s]

    def write(self, write_str):
        final_bytes = write_str.encode('utf8')
        self.process.stdin.write(final_bytes)
        self.process.stdin.flush()

    def write_line(self, write_str):
        final_bytes = (write_str+'\n').encode('utf8')
        self.process.stdin.write(final_bytes)
        self.process.stdin.flush()


command = 'py -3 want_right.py'

pi = ProcessInteraction(command)
for i in range(2):
    content = pi.read_util_re(r'input (\d+): ')
    print(content[0])
    num = content[1].group(1)
    print(repr(num))
    pi.write_line(num)
content = pi.read_line()
print(content)

输出是:

input 5:
'5'
input 0:
'0'
Right!

【讨论】:

    猜你喜欢
    • 2012-12-26
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 2014-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多