Reputation: 6815
I am writing a python script which utilises the Chrome Devtools protocol (I am using the Python wraper PyChromeDevTools headless Chrome, but I need to have an instance of Chrome already running. I would like the script to launch a headless Chrome instance, at the beggining, and close it at the end.
I have tried this:
import subprocess
CHROME_PATH=r'C:\Program Files (x86)\Google\Chrome\Application\chrome'
chrome_args=[CHROME_PATH,
'--headless',
'--disable-gpu',
'--remote-debugging-port=7912',
r'https://www.youtube.com/',]
cmd=r" ".join(chrome_args)
subprocess.call(cmd)
This seems to work (if I navigate to localhost:7912 I see that headless Chrome has started and there is a tab opened with https://www.youtube.com and also a worker pid (which disappears when I kill the python process). But the python script just hangs there, it doesn't continue to run the rest of the script.
How can I launch headless Chrome so that the script continues. Also, how can I kill this process when I have finished with it?
(If I run the same script, but don't ask for Chrome to be headless, the script continues as expected).
Upvotes: 1
Views: 1727
Reputation: 8754
You'll want p = subprocess.Popen(chrome_args)
. Unlike subprocess.call
, this doesn't wait for the spawned process to terminate, and just runs it in the background. Be advised, however, that if your script finishes, Chrome might be killed too. So you could either wait for Chrome to terminate with p.wait
or stall the script with e.g. input()
.
Upvotes: 2