How to create a thread in Python?

4

I am writing a code but it has not worked as expected. A simplified version of the code is like this:

from subprocess import call
import time

call([r"C:\Windows\System32\notepad.exe"])
time.sleep(5)
call(["taskkill", "/im", "notepad.exe"])

When you run the script above, the code does not run from the line of the first call , that is, the script opens the notepad and waits for a response of call([r"C:\Windows\System32\notepad.exe"]) , but this only happens when I manually close the notepad.

I would like the script to open the notepad, wait 5 seconds and close it, without manual user intervention. So, how can I do it?

    
asked by Math 15.01.2016 в 18:35
source

1 answer

6

What you can do is use Popen instead of call :

process = subprocess.Popen('C:\Windows\System32\notepad.exe')

The subprocess.call function waits for the command to complete, is for that which returns the execution control when you close the notepad.exe .

The subprocess.Popen function is executed in a new (child) process.

After the sleep , you can use the Popen.kill function to finish the process:

import subprocess
import time

process = subprocess.Popen('C:\Windows\System32\notepad.exe')
time.sleep(5)
process.kill()

If you want to interact with the subprocess using Popen (send data to stdin , read from stdout or stderr ), you can use the function Popen.communicate :

import subprocess

process = subprocess.Popen('C:\comando.exe')
print 'Durante el proceso'
stdout, stderr = process.communicate() # Esperando
print 'Fin del proceso'

But keep in mind that Popen.communicate waits for the completion of the subprocess, therefore, it is no longer necessary to use Popen.kill

    
answered by 15.01.2016 / 19:47
source