How to execute command in terminal with python script?

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

./driver.exe bondville.dat 

This command is printed in the terminal, but it is not executed.

Here are my steps:

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

He should execute the command, but just print it on the terminal. When feeding the same by hand, it is performed. How to do this from a script?

+7
python shell terminal
source share
3 answers

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

You print echo driver.exe bondville.dat and do you run 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) 
+9
source share

You can use the subprocess.check_call module to run the command, you do not need to echo the command to run:

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

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

If you want to get the result, you will use check_outout :

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

In your own code, you basically repeat the command line, which does not actually execute the ie echo "./driver.exe bondville.dat" , which outputs ./driver.exe bondville.dat to your shell.

+2
source share

Try the following:

 import subprocess subprocess.call("./driver.exe bondville.dat") 
+2
source share

All Articles