- 1 year ago
Python subprocess launch Android virtual device but can't terminate and get wrong PID
When using the subprocess
module in Python to launch an Android virtual device (AVD), terminating the process can sometimes be challenging due to the way the AVD is started and managed. Additionally, the process ID (PID) obtained from the subprocess
module may not correspond to the actual PID of the AVD.
To properly terminate the AVD process, you can follow these steps:
Use the
subprocess.Popen
method: Launch the AVD using thesubprocess.Popen
method, which allows you to manage and control the subprocess.pythonimport subprocess
avd_process = subprocess.Popen(["emulator", "@avd_name"])
Replace
"@avd_name"
with the name of your AVD.Wait for the AVD to start: After launching the AVD, wait for it to start and become fully operational. You can add a delay to allow sufficient time for the AVD to initialize.
pythonimport time
time.sleep(10) # Adjust the delay as needed
Terminate the AVD process: To terminate the AVD, you can use the
subprocess.Popen.terminate
method to send a termination signal to the process.pythonavd_process.terminate()
Verify termination: Check if the AVD process has terminated by using the
subprocess.Popen.poll
method. If the return value isNone
, the process is still running. Wait for the process to terminate before continuing with your code.pythonavd_process.poll()
while avd_process.returncode is None:
time.sleep(1)
avd_process.poll()
This loop will keep checking the return code until the AVD process has terminated.
Please note that the PID returned by subprocess.Popen.pid
may not correspond to the actual PID of the AVD process. The AVD process may spawn additional child processes, resulting in different PIDs. Therefore, it's recommended to use the terminate
and poll
methods as described above to ensure proper termination of the AVD process.
Adjust the code as needed based on your specific requirements and the behavior of the AVD process on your system.