[英]How to run several times the same program with different inputs via Python script?
I need to run a simple C program several time, each one with different input string (let's say AAAAA... increasing size, until I get "TRUE" as output). 我需要多次运行一个简单的C程序,每个程序都有不同的输入字符串(让我们说AAAAA ...增加大小,直到我得到“TRUE”作为输出)。 eg
例如
./program A # output FALSE
./program AA # output FALSE
./program AAA # output FALSE
./program AAAA # output FALSE
./program AAAAA # output FALSE
./program AAAAAA # output FALSE
./program AAAAAAA # output TRUE
in CI would simply use a while loop. 在CI中只需使用while循环。 I know in python there is the while loop as well.
我知道在python中也有while循环。
So the python program would be: 所以python程序将是:
strlen = 0
while TRUE
strlen++
<run ./**C program** "A"*strlen >
if (<program_output> = TRUE)
break
Given that I can make the .py script executable by writing 鉴于我可以通过编写使.py脚本可执行
#! /usr/bin/env python
and 和
chmod +x file.py
What should I do to make this work? 我应该怎么做才能使这项工作?
Thanks in advance 提前致谢
You can use subprocess.check_output : 您可以使用subprocess.check_output :
import subprocess
strlen = 0
while True:
strlen += 1
if subprocess.check_output(['./program', 'A'*strlen]) == 'TRUE':
break
You could try something like this (see docs ): 你可以试试这样的东西(见文档 ):
import subprocess
args = ""
while True:
args += "A"
result = subprocess.call(["./program", "{args}".format(args=args)])
if result == 'TRUE':
break
The subprocess
module is preferred to the os.popen
command, since it has been "deprecated since version 2.6." subprocess
os.popen
模块比os.popen
命令更os.popen
,因为它自“2.6版本以来已被弃用”。 See the os documentation . 请参阅os文档 。
file.py file.py
import os
count=10
input="A"
for i in range(0, count):
input_args=input_args+input_args
os.popen("./program "+input_args)
running file.py would execute ./program 10 times with increasing A
input 运行file.py会在增加
A
输入的情况下执行./program 10次
Use commands
. 使用
commands
。 Here is the documentation http://docs.python.org/2/library/commands.html
这是文档
http://docs.python.org/2/library/commands.html
commands.getstatusoutput
returns a stdout output from your C program. commands.getstatusoutput
返回C程序的stdout输出。 So, if your program prints something, use that. commands.getstatus
returns boolean status from program which you can use as well. commands.getstatus
从程序中返回布尔状态,您也可以使用它。 So, assuming you are using stdout to capture the ./program
output, the entire modified program looks like 因此,假设您使用stdout捕获
./program
输出,整个修改过的程序看起来像
import commands
while TRUE:
strlen += 1
output = commands.getstatusoutput("./program " + "A"*strlen)
outstatus = output[1]
if output == "true":
break
I would experiment with getstatus
to see if I can read values returned by program
. 我会尝试使用
getstatus
来查看是否可以读取program
返回的值。
Edit: Didn't notice that commands
is deprecated since 2.6 Please use subprocess
as shown in other response. 编辑:没有注意到自2.6以来不推荐使用
commands
请使用其他响应中显示的subprocess
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.