首页 > 编程语言 > 详细

python---命令行程序的自动交互

时间:2020-05-25 23:49:51      阅读:65      评论:0      收藏:0      [点我收藏+]

以这个python程序为例:

# 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!‘)

用脚本调用这个程序,并自动输出 ‘Rignt!‘,使用 subprocess 实现:

# 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!

感谢 zl

20200525

python---命令行程序的自动交互

原文:https://www.cnblogs.com/-rvy-/p/12961420.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!