Python3 TOR Browser Example using STEM
Start new TOR Proxy, Connect to existing TOR Proxy, Test TOR Proxy and Kill the TOR Proxy session examples.

Create TOR Proxy Session


# complete code found in create_basic_tor_proxy.py
import os
import re

import stem.process

SOCKS_PORT = 9050
CONTROL_PORT = 9051
TOR_PATH = os.path.normpath("C:\\Users\\Admin\\Documents\\Tor\\tor\\tor.exe")
tor_process = stem.process.launch_tor_with_config(
    config={
        'SocksPort': str(SOCKS_PORT),
        'ControlPort': str(CONTROL_PORT),
        'GeoIPFile': 'https://raw.githubusercontent.com/torproject/tor/main/src/config/geoip',
        'StrictNodes' : '1',
        'CookieAuthentication' : '1',
        'MaxCircuitDirtiness' : '60'
    },
    init_msg_handler=lambda line: print(line) if re.search('Bootstrapped', line) else False,
    tor_cmd=TOR_PATH
)

Connect to exisiting TOR Proxy Session

from stem.control import Controller

CONTROL_PORT = 9051
tor_controller = Controller.from_port(port=CONTROL_PORT)
tor_controller.authenticate()

exit_nodes = tor_controller.get_network_statuses()

for node in exit_nodes:
    print(node)

Test TOR Proxy Session

import json
from datetime import datetime

import requests

PROXIES = {
    'http': 'socks5://127.0.0.1:9050',
    'https': 'socks5://127.0.0.1:9050'
}
response = requests.get("http://ip-api.com/json/", proxies=PROXIES)
result = json.loads(response.content)
print('TOR IP [%s]: %s %s' % (datetime.now().strftime("%d-%m-%Y %H:%M:%S"), result["query"], result["country"]))

Kill TOR Proxy Session

import psutil

process_name = 'tor.exe'
for process in psutil.process_iter(['pid', 'name']):
    if process.info['name'] == process_name:
        print(f"Killing process {process.info['name']} with PID {process.info['pid']}")
        process.terminate()
        break