[Tutor] os command
Hugo González Monteverde
hugonz-lists at h-lab.net
Wed Nov 2 22:39:25 CET 2005
In UNIX, you use the fork() exec() technique for starting a new process,
from the very first process(init) onwards. The os.system() uses a shell
to do that, or you may do it yourself (in your script)
A "command" is just an executable file running(process), unless you've
got a library function that does just that, then you could do what you
must without creating a new process.
Probably your best bet would be to use the subprocess module. It was
designed around the limitations of the previous methods.
Take a look at what oyu can do with it at:
http://www.python.org/doc/2.4.2/lib/module-subprocess.html
For example, the pid of the command would be available at the pid
atribute of a subprocess instance.
p.pid
Hugo
Johan Geldenhuys wrote:
> Sorry for the late reply,
> But is it necessary to use a child process? I don't want to execute the
> command in another process. What happens with the parent process and how
> do I execute my command in the parent process?
>
> Thanks
>
> Hugo González Monteverde wrote:
>
>> Hi,
>>
>> os.system will return the errorval of the application. You need to
>>
>> 1) get the pid of the child process
>> 2) kill it using os.kill(os.SIGTERM)
>> 3) reap the killed process
>>
>> This is all in unix/linux, of course.
>>
>> what I do (untested, please check order of args and correct usage of
>> exec):
>>
>> pid = os.fork()
>>
>> if pid == 0: #child process
>> os.execvp("tcpdump", "tcpdump", "-n", "-i", "eth0")
>>
>> else: #parent
>> time.sleep(5)
>> os.kill(pid, os.SIGTERM)
>> os.waitpid(pid, 0) #wait for process to end
>>
>>
>>
>> Johan Geldenhuys wrote:
>>
>>> I have script that calls a system command that I want to run for 5
>>> minutes.
>>> """
>>> import os
>>> cmd = 'tcpdump -n -i eth0'
>>> os.system(cmd)
>>> """
>>>
>>> I can start a timer after the cmd is issued, but I don't know how to
>>> send a control signal to stop the command after I issued it. This is
>>> normally from the shell ^c.
>>>
>>> This cmd my run in more than one thread on different interfaces and I
>>> don't whant all of then stopped at once. I think the best way is to
>>> make a thread for each interface where the cmd can be issued and
>>> stopped without the danger of stopping he wrong thread.
>>>
>>> Can anybody help?
>>>
>>> Thanks
>>>
>>> Johan
>>> _______________________________________________
>>> Tutor maillist - Tutor at python.org
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>
>
More information about the Tutor
mailing list