Hi all.


i want to make separate process with python.

for example i have python code. for example:

import time
time.sleep(5)
print "Time Over"

named: t.py

and i want to do all ^^that^^ just on other process :)
i hope you understand.


AND DONT GIVE ME LINKS PLS. I GOOGLED THAT MUCH.
BUT NOTHING HELPFUL,
just WRITE CODE WHICH WOULD BE HELPFUL FOR ME! :)
sorry for My english :)

One way to do it is to use the subprocess module

import subprocess as SP
child_process = SP.Popen(["python", "t.py"])
commented: thx +0

Not sure what your asking?

Do you mean you want to create:

1. a thread which exists in the current process
2. a new process which exists independently

you're not making much sense... Do you want to have that processes running on another thread so you can continue doing something else? Do you just want to execute that little script then after it finishes it moves on? What are you trying to do EXACTLY?

Gribouillis

and where can i donwload thatmodule?

gerard4143
2:D


ov3rcl0ck
I want to have that processes running on another thread and ability to continue doing something else.:)
and
I DONT want just to execute that little script then after it finishes it moves on. :)

ov3rcl0ck, for example, i have code:


...commands1...
...commands2...
call to t.py and imediately go on next command3
...commands3...
...commands4...

and i think separate process is the best in this time :)

Gribouillis

and where can i donwload thatmodule?

gerard4143
2:D


ov3rcl0ck
I want to have that processes running on another thread and ability to continue doing something else.:)
and
I DONT want just to execute that little script then after it finishes it moves on. :)

ov3rcl0ck, for example, i have code:


...commands1...
...commands2...
call to t.py and imediately go on next command3
...commands3...
...commands4...

and i think separate process is the best in this time :)

First off Subprocess is a default module for python, next subprocess doesn't spawn a new thread, you need the multithreading module that comes default with the interpreter, also knowing object orientated programming will help. Try this little example:

import threading

class THREAD(threading.Thread):
	def __init__(self,ARG1,ARG2):
		#If you change the arugments of __init__ modify the bellow also
		self.arg1=ARG1
		self.arg2=ARG2
	def run(self):
		#THIS IS WERE YOUR CODE GOES!

t=THREAD(ARG1,ARG2)
t.start()
t.join()

The easiest way to do it is make a thread out of a function but this will lose alot of functionality and is a messy way of doing things IMO. Here it is:

import threading,thread

def THREAD(ARG1,ARG2):
	#YOUR CODE
thread.start_new_thread(THREAD, (ARG1,ARG2))

code:

import threading
 
class THREAD(threading.Thread):
	def __init__(self,ARG1,ARG2):
		#If you change the arugments of __init__ modify the bellow also
		self.arg1=ARG1
		self.arg2=ARG2
	def run(self):
		print "RUN"
		#THIS IS WERE YOUR CODE GOES!
ARG1,ARG2=1,2

t=THREAD(ARG1,ARG2)
t.start()
t.join()

error:
Traceback (most recent call last):
File "D:\Desktop_MARI\threading\th.py", line 14, in <module>
t.start()
File "C:\Python25\lib\threading.py", line 432, in start
raise RuntimeError("thread.__init__() not called")
RuntimeError: thread.__init__() not called

import threading
 
class THREAD(threading.Thread):
	def __init__(self,ARG1,ARG2):
		threading.Thread.__init__(self)
		#If you change the arugments of __init__ modify the bellow also
		self.arg1=ARG1
		self.arg2=ARG2
	def run(self):
		print "RUN"
		#THIS IS WERE YOUR CODE GOES!
ARG1,ARG2=1,2

t=THREAD(ARG1,ARG2)
t.start()
t.join()

Forgot a line. But you do realize this is an example and i posted it so you can adjust it to your needs, if you don't understand it you're not ready for threading, so this script probably won't work, and if it does its not gonna do anything.If you don't understand it you're not ready for threading.

commented: thx +0

overclock, that isnot what i need.however,thank you .

Gribouillis, that was usefull. however i want to know how to multiproceess. i dont believe that it isnt possible.

Multi processing is similar to threading, google "python multiprocess"

Multiprocessing and threading are fairly similar, in fact multiprocessing is based off the multithreading API. Heres a really really easy example:

from multiprocessing import Process

def f(name):
    print 'hello', name

if __name__ == '__main__':
    p = Process(target=f, args=('bob',)) #inits thread
    p.start() #starts thread
    p.join() #waits untill thread is done

multiprossessing is a standard module for python >= 2.6. For older versions, you must download pyprocessing.

i downloaded pyprocess. installed an=d got error:
'module' object has no attribute 'f'

i downloaded pyprocess. installed an=d got error:
'module' object has no attribute 'f'

post your code

gribilus, overclock's code:

from multiprocessing import Process
 
def f(name):
    print 'hello', name
 
if __name__ == '__main__':
    p = Process(target=f, args=('bob',)) #inits thread
    p.start() #starts thread
    p.join() #waits untill thread is done

gribilus, overclock's code:

from multiprocessing import Process
 
def f(name):
    print 'hello', name
 
if __name__ == '__main__':
    p = Process(target=f, args=('bob',)) #inits thread
    p.start() #starts thread
    p.join() #waits untill thread is done

On my machine it works well with python 2.6.

i have 2.5

2.6 has many bugs so i prefer 2.5

2.6 has many bugs so i prefer 2.5

2.6 has been out for a while now, its pretty safe to use.

This works with Python 2.5 ...

# from http://pypi.python.org/pypi/processing installed:
# processing-0.52.win32-py2.5.exe

from processing import Process

def func(name):
    print 'hello %s' % name

if __name__ == '__main__':
    # initialize thread
    p = Process(target=func, args=('bob', ))
    # starts thread
    p.start()
    # waits until thread is done
    p.join()
commented: thx +0

your codes solve my problem but i am interested multi process. conjunction or i want to open other cmd. ok if you dont understand never mind.:)

+rep to all

but i am interested multi process

This is an example of multiprocessing/pyprocessing running 2 threads and passing variables back and forth via a dictionary.

import time
from multiprocessing import Process, Manager

def test_f(test_d):
   """  frist process to run
        exit this process when dictionary's 'QUIT' == True
   """
   test_d['2'] = 2     ## change to test this
   while not test_d["QUIT"]:
      print "test_f", test_d["QUIT"]
      test_d["ctr"] += 1
      time.sleep(1.0)

def test_f2(name):
    """ second process to run.  Runs until the for loop exits
   """
    for j in range(0, 10):
       print name, j
       time.sleep(0.5)

    print "second process finished"
    
if __name__ == '__main__':
   ##--- create a dictionary via Manager
   manager = Manager()
   test_d = manager.dict()
   test_d["ctr"] = 0
   test_d["QUIT"] = False
   
   ##---  start first process and send dictionary
   p = Process(target=test_f, args=(test_d,))
   p.start()
   
   ##--- start second process
   p2 = Process(target=test_f2, args=('P2',))
   p2.start()

   ##--- sleep 2 seconds and then change dictionary
   ##     to exit first process
   time.sleep(2.0)
   print "\nterminate first process"
   test_d["QUIT"] = True
   print "test_d changed"
   print "data from first process", test_d

   ##---  may not be necessary, but I always terminate to be sure
   time.sleep(5.0)     ## let 2nd process finish
   p.terminate()
   p2.terminate()

oh no,you just cant understand, ok,i explain once again when you run py program its open ONE console, and i want to open ONE ---ANOTHER--- CONSOLE.

oh no,you just cant understand, ok,i explain once again when you run py program its open ONE console, and i want to open ONE ---ANOTHER--- CONSOLE.

well then try this for windows, remember to launch it in its own process/thread though:

import os
os.system("python YOURSCRIPT.py")

or try this for linux:

import os
os.system("xterm python YOURSCRIPT.py")

for linux you need to launch a new terminal/shell otherwise it is run in the background.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.