Skip to main content
2 of 2
Commonmark migration

A word on indentation

You have mismatched indentation levels in tor_browser_initialise (shouldn't it be "initialize"?): 8 spaces at the beginning and then 4. Choose only one and stick to it. PEP 8 recommend 4 spaces.

It also has some recommendation on aligning continuation lines. You'd better of be using

useragent_list = [
    'Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 '
        'Firefox/31.0',
    'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 '
        'Firefox/29.0',
    'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 '
        '(KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36',
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 '
        '(KHTML, like Gecko) Chrome/36.0.1944.0 Safari/537.36',
    'Mozilla/5.0 (compatible; MSIE 10.6; Windows NT 6.1; '
        'Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; '
        '.NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0',
    'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)',
    'Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14',
    'Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) '
        'AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30'
]

Which also uses implicit string literals continuation to keep line length under 80 characters.

Use constants as such

LOCALHOST, PORT, and useragent_list are constants, you even use uppercase for two of them to emphasize it. Why redefine them each time you call connect_tor, then?

You should move them from the function body to the top-level of the file. You may also be interested in turning useragent_list (or USER_AGENTS which I find better) into an immutable collection such as a tuple or a frozenset.

Save on resources and computation

You could improve tor_browser_initialise by returning early if you find the 'tor.exe' process. You could thus get rid of the processlist since exitting the for loop would mean that you didn't return early and thus you didn't find the process you were looking for.

def tor_browser_initialise():
    for p in psutil.process_iter():
        try:
            process = psutil.Process(p.pid)
            if process.name() == 'tor.exe':
                return
        except:
            continue

    subprocess.Popen(
        r"C:\Program Files (x86)\Tor Browser\Browser\firefox.exe",
        stdout=subprocess.PIPE)
    time.sleep(30)