Luke25361
Luke25361

Reputation: 185

How to hide output of subprocess in Python without preventing other subprocesses from running

I run Python 3.3.5 on Windows, and a very basic version of something I'm working on looks like this:

import os
import subprocess
import time
path = r"C:\Users\Luke\Desktop\Tor_Browser\Browser\firefox.exe {0}"
url = "http://google.com"
views = 5
opened = 0
for i in range(views):
    subprocess.Popen(path.format(url))
    time.sleep(15)
    opened = opened + 1
    print ("Times opened:", opened)
    os.system("taskkill /f /im firefox.exe")

What this code is supposed to do is run my firefox/tor browser with the google url 5 times for 15 seconds each and then close it. It does just this, however, I can't seem to stop the terminal from displaying the text: "SUCCESS: The process "firefox.exe" with PID xxxx has been terminated."

I've tried changing the line

os.system("taskkill /f /im firefox.exe")

to

FNULL = open(os.devnull, 'w')    
subprocess.Popen("taskkill /f /im firefox.exe", stdout=FNULL)

but when I do the program only opens the browser once, closes it and then ceases to open it again but still displays the "Times opened" text.

Anyone have any ideas as to how I can stop the terminal from displaying this text?

Thanks

-Luke

Upvotes: 0

Views: 913

Answers (1)

a p
a p

Reputation: 3208

Try this:

import os
import subprocess
import time
path = r"C:\Users\Luke\Desktop\Tor_Browser\Browser\firefox.exe {0}"
url = "http://google.com"
views = 5
opened = 0
for i in range(views):
    proc = subprocess.Popen(path.format(url))   # Change here to bind pipe to a name
    time.sleep(15)
    opened = opened + 1
    print ("Times opened:", opened)
    proc.terminate()                            # send process term signal

Upvotes: 1

Related Questions