Click here to Skip to main content
15,885,990 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
my python code goes like this:

def a():
...
...
subprocess.call()
...
...

def b():
...
...

and so on.

My task:
1) If subprocess.call() returns within 3 seconds, my execution should continue the moment subprocess.call() returns.
2) If subprocess.call() does not return within 3 seconds, the subprocess.call() should be terminated and my execution should continue after 3 seconds.
3) Until subprocess.call() returns or 3 seconds finishes, the further execution should not take place.

This can be done with threads but how?


Relevant part of the real code goes like this:

...
VB
cmd = ["gcc", srcname, "-o", execname];
p = subprocess.Popen(cmd,stderr=errfile)#compiling C program

...
...
VB
inputfile=open(input,'w')
inputfile.write(scanf_elements)
inputfile.close()
inputfile=open(input,'r')
tempfile=open(temp,'w')
                     subprocess.call(["./"+execname,str(commandline_argument)],stdin=inputfile,stdout=tempfile);#executing C program
tempfile.close();

...
...

I am trying to compile and execute a C program using python.
When I am executing C program using subprocess.call() and suppose if the C program contains an infinite loop, then the subprocess.call() should be terminated after 3 seconds and the program should continue. I should be able to know whether the subprocess.call() was forcefully terminated or successfully executed so that I can accordingly print the message in the following code.
Posted
Updated 17-Jan-15 1:41am
v2

1 solution

Implement some form of timer in your main thread to check whether the call has returned. See https://docs.python.org/3.3/library/threading.html#module-threading[^], for more information.
 
Share this answer
 
Comments
875ewh84 17-Jan-15 0:44am    
you mean to say:

t=Timer(3,function_name)
t.start()

combining thread.start_new_thread() and Timer, I have tried many permutation and combination but all the above 3 conditions are not getting satisfied.
Richard MacCutchan 17-Jan-15 4:33am    
I have tried many permutation and combination
Then you should update your question and show the exact code, and explain what problems it creates.
875ewh84 17-Jan-15 7:42am    
Question updated.
875ewh84 17-Jan-15 0:50am    
Although 3 conditions are appearing simple,I personally feel that it is difficult to code.
Richard MacCutchan 17-Jan-15 4:34am    
No one ever said it would be easy.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900