python控制其它软件_从另一个脚本控制python脚本
我正在嘗試學(xué)習(xí)如何編寫(xiě)一個(gè)腳本control.py,它在循環(huán)中運(yùn)行另一個(gè)腳本test.py一定次數(shù),在每次運(yùn)行中,讀取其輸出并在打印某些預(yù)定義輸出時(shí)暫停它(例如文本’現(xiàn)在停止’),并且循環(huán)繼續(xù)其迭代(一旦test.py完成,無(wú)論是單獨(dú)還是強(qiáng)制).所以有一些事情:
for i in range(n):
os.system('test.py someargument')
if output == 'stop now': #stop the current test.py process and continue with next iteration
#output here is supposed to contain what test.py prints
>上面的問(wèn)題是,它不會(huì)檢查test.py正在運(yùn)行的輸出,而是等到test.py進(jìn)程自行完成,對(duì)吧?
>基本上嘗試學(xué)習(xí)如何使用python腳本來(lái)控制另一個(gè),因?yàn)樗谶\(yùn)行. (例如,可以訪(fǎng)問(wèn)它打印的內(nèi)容等).
>最后,是否可以在新終端(即不在control.py的終端中)運(yùn)行test.py并仍然實(shí)現(xiàn)上述目標(biāo)?
嘗試:
test.py是這樣的:
from itertools import permutations
import random as random
perms = [''.join(p) for p in permutations('stop')]
for i in range(1000000):
rand_ind = random.randrange(0,len(perms))
print perms[rand_ind]
而control.py是這樣的:(遵循Marc的建議)
import subprocess
command = ["python", "test.py"]
n = 10
for i in range(n):
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
output = p.stdout.readline().strip()
print output
#if output == '' and p.poll() is not None:
# break
if output == 'stop':
print 'sucess'
p.kill()
break
#Do whatever you want
#rc = p.poll() #Exit Code
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的python控制其它软件_从另一个脚本控制python脚本的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 安卓软件名称修改(安卓名称修改)
- 下一篇: linux的磁盘管理(linux的磁盘)