python - Non blocking subprocess.call -


i'm trying make non blocking subprocess call run slave.py script main.py program. need pass args main.py slave.py once when it(slave.py) first started via subprocess.call after slave.py runs period of time exits.

main.py insert, (list) in enumerate(list, start =1):      sys.args = [list]     subprocess.call(["python", "slave.py", sys.args], shell = true)   {loop through program , more stuff..} 

and slave script

slave.py print sys.args while true:     {do stuff args in loop till finished}     time.sleep(30) 

currently, slave.py blocks main.py running rest of tasks, want slave.py independent of main.py, once i've passed args it. 2 scripts no longer need communicate.

i've found few posts on net non blocking subprocess.call of them centered on requiring communication slave.py @ some-point not need. know how implement in simple fashion...?

you should use subprocess.popen instead of subprocess.call.

something like:

subprocess.popen(["python", "slave.py"] + sys.argv[1:]) 

from docs on subprocess.call:

run command described args. wait command complete, return returncode attribute.

(also don't use list pass in arguments if you're going use shell = true).


here's mcve1 example demonstrates non-blocking suprocess call:

import subprocess import time  p = subprocess.popen(['sleep', '5'])  while p.poll() none:     print('still sleeping')     time.sleep(1)  print('not sleeping longer.  exited returncode %d' % p.returncode) 

an alternative approach relies on more recent changes python language allow co-routine based parallelism is:

# python3.5 required modified work python3.4. import asyncio  async def do_subprocess():     print('subprocess sleeping')     proc = await asyncio.create_subprocess_exec('sleep', '5')     returncode = await proc.wait()     print('subprocess done sleeping.  return code = %d' % returncode)  async def sleep_report(number):     in range(number + 1):         print('slept %d seconds' % i)         await asyncio.sleep(1)  loop = asyncio.get_event_loop()  tasks = [     asyncio.ensure_future(do_subprocess()),     asyncio.ensure_future(sleep_report(5)), ]  loop.run_until_complete(asyncio.gather(*tasks)) loop.close() 

1tested on os-x using python2.7 & python3.6


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -