1

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).

1 Answer 1

2

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().

Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant thanks. Been trying to figure this out for ages. Annoying there was such a simple solution. Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.