2014-03-05 37 views
2

我需要多次运行一个简单的C程序,每个程序都有不同的输入字符串(假设AAAAA ...增加大小,直到获得“TRUE”作为输出)。 例如如何通过Python脚本通过不同的输入运行几次相同的程序?

./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 

用C我会简单地用一个循环。 我知道在Python中有循环。

所以python的程序是:

strlen = 0 
while TRUE 
strlen++ 
<run ./**C program** "A"*strlen > 
if (<program_output> = TRUE) 
    break 

既然我可以做的.py可执行脚本写

#! /usr/bin/env python 

chmod +x file.py 

我应该怎么做做这个工作?

在此先感谢

+0

...这不是一个Python程序 – jonrsharpe

+0

我知道,语法是不正确的。这只是一个例子 – dragonmnl

回答

2

执行./program 10倍,您可以尝试一些像这样(见docs):

import subprocess 

args = "" 
while True: 
    args += "A" 
    result = subprocess.call(["./program", "{args}".format(args=args)]) 
    if result == 'TRUE': 
     break 

subprocess模块优于os.popen命令,因为它已从版本2.6开始被弃用。请参阅os documentation

+0

程序不是的.py脚本,而是一个C程序 – dragonmnl

+0

请看到我的编辑答案。代码起作用 – JohnZ

+0

。你为什么要用“args”?但是,每次执行后程序(./program)需要用户中断(ctrl + C)停止。显然,如果我这样做,程序./程序以及.py程序都存在。有没有人让./程序退出,但.py继续? – dragonmnl

1

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) 

运行file.py将随着A输入

+0

程序不是的.py脚本,而是一个C程序 – dragonmnl

+0

@dragonmnl所做的更改运行'program'为可执行 –

4

您可以使用subprocess.check_output

import subprocess 
strlen = 0 
while True: 
    strlen += 1 
    if subprocess.check_output(['./program', 'A'*strlen]) == 'TRUE': 
     break 
+0

我试过了代码。它似乎工作..但1循环后只有它卡住了。我试图把打印(strlen的)后的strlen + = 1,事实上它打印1只,仅此而已(也不是程序退出) – dragonmnl

+0

它为我工作。程序是否退出?与返回码0? –

+0

实际上它没有。他在每次执行后编程(./program)需要用户中断(ctrl + C)停止。显然,如果我这样做,程序./程序以及.py程序都存在。有没有人让./程序退出,但.py继续? – dragonmnl

1

使用commands。这里是文档http://docs.python.org/2/library/commands.html

  1. commands.getstatusoutput从你的C程序返回一个stdout输出。所以,如果你的程序打印了一些东西,就用它。 (事实上​​,它为stdout返回一个元组(0,out))。
  2. commands.getstatus从程序返回布尔状态,您也可以使用该状态。

因此,假设你正在使用标准输出捕捉./program输出,整个修改后的程序看起来像

import commands 

while TRUE: 
    strlen += 1 
    output = commands.getstatusoutput("./program " + "A"*strlen) 
    outstatus = output[1] 
    if output == "true": 
    break 

我将与getstatus实验,看看我是否可以读取program返回的值。

编辑:没有注意到commands已被弃用,因为2。6请使用subprocess,如其他回复所示。

+2

**不要**使用'命令'。使用['subprocess'模块(http://docs.python.org/2/library/subprocess.html)来代替。在为'commands'文档顶部的大发警告会告诉你:*自从2.6版本*已过时。 –

+0

哎呀..没有注意到已弃用的部分。我最近用过它,不是最近 –

相关问题