I am trying to make a script to automatically browse a URL in Tor browser and after a few second terminate the process on the windows.
everything works fine actually, python randomly chooses a line in my URL.text file and open it in Tor browser using an OS command then I added a sleep.time
for a short wait before terminating the process, but when I execute the code it waits on "os.system" until I manually close the browser. After that, the rest of the code executes fine.
What is wrong here? I can't find it.
Why does python wait on os.system
line until I close the browser? Why doesn't it execute sleep
after executing os.system
command automatically?
import time
import subprocess
import os
import random
def random_line(afile):
line = next(afile)
for num, aline in enumerate(afile, 2):
if random.randrange(num): continue
line = aline
return line
i = 1
while i == 1:
with open("C:\\Users\\TPK\\PycharmProjects\\MyScripts\\venv\\urls.txt" , "r") as urlfile:
rndurl = random_line(urlfile)
tor = "\"C:\\Users\\TPK\\PycharmProjects\\MyScripts\\venv\\TorBrowser\\Start Tor Browser.lnk\" " + rndurl
os.system(tor)
time.sleep(5)
print ("after sleep")
os.system("taskkill /im firefox.exe")
The way that os.system
works is that it does not spawn a new process running in the background. Instead, it waits for the command to finish running and then continues on. In your case, the process finishes when you close the browser window. Rather than using os.system
, I would recommend that you use subprocess.run
. Instead of waiting for the process to finish, it spawns it and lets it run in the background. Just note that you will need to separate the command at each space and put it in a list. Like so: subprocess.run(["C:\path\to\Start Tor Browser.lnk", "https://url.to.open"])