1

I have a C++ Visual Studio program called Test which takes two arguments. I have to run this program with large number of different arguments like:

  • ./test -a -b (a is arg1, b is arg2)
  • ./test -c -d
  • .
  • .
  • .

How can I create a python script which runs this program multiple times if I provide the set of arguments? (instead of me running the above command multiple times).

Soln: This is the code I used:

for commands in listargs:
    cmd = ["../../Test.exe", commands[0], commands[1]]
    result = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    stdin, stderr = result.communicate()
    print stdin

I am giving the arguments in a list of 2-member tuples(listargs). Each tuple has the arguments for one execution. Or as abernet mentioned, we can give arguments in csv file. Thanks for helping me.

2
  • What do you mean by "c++ visual studio program"? Do you just mean an executable (which you happen to have compiled with Visual Studio's C++ compiler)? Commented May 26, 2015 at 23:05
  • More importantly, how do you want to provide the set of arguments? Do you want to type in a and b at a prompt? Or create a CSV file with rows like a,b? Or …? Commented May 26, 2015 at 23:06

2 Answers 2

1

For this type of stuff, you should use subprocess, possibly subprocess.communicate:

p = subprocess.Popen(['./test', '-' + a, '-' + b])
p.communicate()

This is a very versatile command that will also allow you to redirect inputs and outputs. See PMOTW.

Sign up to request clarification or add additional context in comments.

Comments

1

You haven't explained how you want to "provide the set of arguments".

Let's say you want to create a CSV file, like this:

a,b
c,d

That's nice and simple to create in a text editor, or you can even do it in Excel.

Python has a csv module in the standard library that knows how to read exactly that format, turning each line into a list of values.

And it has a subprocess module that knows how to run a program with a list of arguments.

So, for example:

with open('args.csv') as f:
    for args in csv.reader(f):
        subprocess.call(['./test'] + args)

If you want to store the output of each run in a file, or check the output and raise an exception on errors, etc., you can do almost anything you want with subprocess, you just have to read the docs.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.