patti_jane patti_jane - 1 month ago 10
Python Question

Killing a program in Python

I have a loop where I run an installed program using

os.system("program + arguments")
passing each element in the loop as an argument to the program. Runtime of the program changes according to the argument, sometimes it takes a second and sometimes it takes hours. So I want to kill the program when it took more than an hour and proceed to the next element in the loop.

I tried to use the second answer here (because I couldn't understand how I could use the best answer) Python: Run a process and kill it if it doesn't end within one hour by replacing
os.sytem("program+arguments")
to
subprocess.Popen(["program+arguments"])

but it gives
"No such file or directory error"
, I'm sure I'm passing the arguments correctly, could you help me how I can apply such solution?

Here is the error message,

subp = subprocess.Popen(["home/admin/Desktop/molblocks/fragment -i " + OrgDir+"/"+compsmi + " -r "+ RulesPath + " -e -n "+str(FragLength) + " -o " + compsmi + "_frag.txt"])

File "/usr/lib64/python2.7/subprocess.py", line 709, in __init__
errread, errwrite)

File "/usr/lib64/python2.7/subprocess.py", line 1326, in _execute_child
raise child_exception


Best Regards!

Answer

On Unix, if args is a string, the string is interpreted as the name or path of the program to execute. However, this can only be done if not passing arguments to the program. (When shell is not True)

https://docs.python.org/2/library/subprocess.html#subprocess.Popen.

Try this:

subp = subprocess.Popen(["home/admin/Desktop/molblocks/fragment", "-i", (OrgDir+"/"+compsmi), "-r", RulesPath, "-e", "-n", str(FragLength), "-o", (compsmi+"_frag.txt")])