Running program prompt in python

129 Views Asked by At

I would like to know how I can use command prompt in python. Here is the thing, I need to run a program which is python based,and I used to do it in command prompt. However, I need to run this program multiple times and, thus, would like to automate it. The program need to run with files in a specific folder, and it uses a config file located in the same specific folder. Finally, I also need it to give a log file once it finishes each process. I used to do all this in command prompt:

C:\Users\Gabriel\Documents\vina_tutorial>"\Program Files (x86)\The Scripps Research Institute\Vina\vina.exe" --config conf.txt --log log.txt

I tried using python:

import subprocess
subprocess.Popen('C:\\Program Files (x86)\\The Scripps Research Institute\\Vina\\vina.exe -config ' + 'conf.txt', cwd='C:\\Users\\Gabriel\\Documents\\vina_tutorial')

However, it didn't seem to work. (I did omit the log file thing in this first step)

Any tips on how to proceed or where I can learn something about it?

1

There are 1 best solutions below

1
On BEST ANSWER

You need to split up your shell command into separate arguments passed into Popen. Read the documentation

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!

Also, you may need to escape the backslashes in the Windows filepath. You may also need to enclose quotes IE '"C:\\Program Files (x86)\\etc..\\foo.exe"'