python 命令列程式的自動化互動

2021-10-09 17:48:57 字數 3334 閱讀 7606

keywords: python 命令列程式 自動化 互動

以這個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:utf-8

# python3

import sys

import re

import subprocess

from threading import thread

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

recvline

(self)

:return self.process.stdout.readline(

).decode(

'utf8'

)def

recv_n

(self, n)

:return self.process.stdout.read(n)

.decode(

'utf8'

)def

recvuntil

(self, want_end_str)

: current_str =

''while

true

: current_str += self.recv_n(1)

if current_str.endswith(want_end_str)

:return current_str

defrecvuntil_re

(self, want_re_str)

: current_str =

''while

true

: current_str += self.recv_n(1)

s = re.search(want_re_str, current_str)

if s:

return

[current_str, s]

defsend

(self, send_str)

: final_bytes = send_str.encode(

'utf8'

) self.process.stdin.write(final_bytes)

self.process.stdin.flush(

)def

sendline

(self, send_str)

: self.send(send_str+

'\n'

)def

interact

(self)

:def

recv_loop()

:while

true

: c = self.recv_n(1)

# print 寫到控制台會有延時,直接用系統io寫

sys.stdout.write(c)

sys.stdout.flush(

)def

send_loop()

:while

true

: send_str =

input()

self.sendline(send_str)

recv_thread = thread(target=recv_loop)

send_thread = thread(target=send_loop)

recv_thread.start(

) send_thread.start(

) recv_thread.join(

) send_thread.join(

)command =

['py'

,'-3'

,'want_right.py'

]pi = processinteraction(command)

for i in

range(2

):content = pi.recvuntil_re(

r'input (\d+): '

)print

(content[0]

) num = content[1]

.group(1)

print

(repr

(num)

) pi.sendline(num)

content = pi.recvline(

)print

(content)

注意:如果在 linux 下執行,command 需要修改為['python3', 'want_right.py']

輸出:

input 5:

'5'input 0:

'0'right!

感謝 zl

&&&&&&& 貌似只對python指令碼好用,exe和elf都不行,讀不到輸出,問題待解決

python 命令列程式的自動互動

keywords python 命令列程式 自動化 互動 以這個python程式為例 coding utf8 python3 import random first num str random.randint 0,10 second num str random.randint 0,10 firs...

Python編寫帶選項的命令列程式

執行python程式時,有時需要在命令列傳入一些引數。常見的方式是在執行時,在指令碼名後直接追加空格分隔的引數列表 例如 python test.py arg0 arg1 arg2 然後在指令碼中就可以通過sys.argv獲取所有的命令列引數。這種方式的優點是傳參方便,引數獲取簡單 缺點是執行指令碼...

XenServer命令列自動化拷貝並初始化虛擬機器

bin bash bootstrap script for hostname,network.author dong guo last modified 2013 10 24 by dong guo options cat proc cmdline sed s rhgb quiet g config...