Reputation: 49
What I want to do is have a python script (that's a python IRC bot) that can run another python script in the background/separately.
I could do something like this:
#irc codey stuff here...
if x == y:
os.system('s%\stuff.py') % path
But this would stop main.py and it then runs stuff.py (in 1 command prompt) which I don't want to do.
So what I am trying to make this script do is when the IRC bot picks up a command via IRC, I want it to run stuff.py separately, like double clicking on stuff.py and having main.py and stuff.py running at the same time.
If there is a separate way of doing this in windows/linux, please, can you show both?
Upvotes: 1
Views: 939
Reputation: 414875
To execute CPU-intensive Python code in the background you could use multiprocessing
:
import multiprocessing as mp
from stuff import some_function
if __name__=='__main__':
pool = mp.Pool()
# ...
if x == y:
pool.apply_async(some_function, args) # use mp.Queue or
# save returned value or
# specify a callback
# to get deferred result from the function
If you go the subprocess
route then to use the same Python launcher as the current script you could try sys.executable
:
import os
import sys
from subprocess import Popen
p = Popen([sys.executable, os.path.join(path, 'stuff.py')])
Upvotes: 0
Reputation: 70354
To open up a separate shell in windows, you could do:
os.system('cmd.exe /c stuff.py')
Or, as others have pointed out, use the subprocess
module. Actually, subprocess
should be a reflex - the tool you grab for, when starting other processes...
Upvotes: 1
Reputation: 3185
The subprocess library may be useful. It allows for background processes and handles some of the forking and child management for you.
Upvotes: 1
Reputation: 5738
To spawn a background process, use the Popen class in the subprocess module.
Example:
from subprocess import Popen
process = Popen(['firefox', '-P', '-no-remote'])
After this process
is a process object that can be used to kill the process, wait for it to finish, communicate with it etc. If you just want to spawn the process and forget about it, you don't need to keep the return value from Popen.
Upvotes: 5