How to run several times the same program with different inputs via Python script?

StackOverflow https://stackoverflow.com/questions/22204801

  •  09-06-2023
  •  | 
  •  

Question

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). e.g.

./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 C I would simply use a while loop. I know in python there is the while loop as well.

So the python program would be:

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

#! /usr/bin/env python

and

 chmod +x file.py

What should I do to make this work?

Thanks in advance

Was it helpful?

Solution 2

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." See the os documentation.

OTHER TIPS

You can use subprocess.check_output:

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

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

Use commands. Here is the documentation http://docs.python.org/2/library/commands.html

  1. commands.getstatusoutput returns a stdout output from your C program. So, if your program prints something, use that. (In fact, it returns a tuple (0, out) for stdout).
  2. commands.getstatus returns boolean status from program which you can use as well.

So, assuming you are using stdout to capture the ./program output, the entire modified program looks like

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.

Edit: Didn't notice that commands is deprecated since 2.6 Please use subprocess as shown in other response.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top