7

I want to execute a command in terminal from a Python script.

 ./driver.exe bondville.dat

This command is getting printed in the terminal, but it is failing to execute.

Here are my steps:

echo = "echo"
command="./driver.exe"+" "+"bondville.dat"
os.system(echo + " " + command)

It should execute the command, but it's just printing it on terminal. When feeding the same thing manually it's executing. How do I do this from a script?

5
  • 2
    Use the subprocess module Commented Oct 11, 2015 at 13:40
  • @PadraicCunningham I am new to python, and this subprocess module seems very difficult for me to handle. How to use this ?
    – dsbisht
    Commented Oct 11, 2015 at 13:43
  • do you want to store the output or just run the command? Commented Oct 11, 2015 at 13:44
  • 1
    Remove the echo to actually run your commands. Now it just prints your command variable contents
    – Samuel
    Commented Oct 11, 2015 at 13:45
  • Possible duplicate of Calling an external command in Python Commented Oct 12, 2015 at 13:07

3 Answers 3

10

The echo terminal command echoes its arguments, so printing the command to the terminal is the expected result.

Are you typing echo driver.exe bondville.dat and is it running your driver.exe program?
If not, then you need to get rid of the echo in the last line of your code:

os.system(command)
0
3

You can use the subprocess.check_call module to run the command, you don't need to echo to run the command:

from subprocess import check_call

check_call(["./driver.exe", "bondville.dat"])

Which is equivalent to running ./driver.exe bondville.dat from bash.

If you wanted to get the output you would use check_outout:

from subprocess import check_output

out = check_output(["./driver.exe", "bondville.dat"])

In your own code you are basically echoing the string command not actually running the command i.e echo "./driver.exe bondville.dat" which would output ./driver.exe bondville.dat in your shell.

2

Try this:

import subprocess
subprocess.call("./driver.exe bondville.dat")
1
  • 1
    "Try this" answers are unhelpful since they don't tell what the problem was or how to fix it next time. Commented Oct 11, 2015 at 16:33

Not the answer you're looking for? Browse other questions tagged or ask your own question.