add-cmd-title.py

Rename the CMD window that's running your Python script.

import os

os.system('title {}'.format('My Python Program'))
create-folder-and-file.py

Create a file, ensure that its folder exists, write some content to it, and save it on demand.

import io
import pathlib

#Files are automatically saved at the end of io.open,
#but you can use this function to save them on demand,
#such as during each iteration of a long loop
def save_file(file):
    file.flush()
    os.fsync(file.fileno())

folder_path = 'lorem/ipsum'
file_name = 'foobar.txt'
file_path = folder_path + '/' + file_name

pathlib.Path(folder_path).mkdir(parents=True, exist_ok=True)

with io.open(file_path, 'a', encoding="utf-8-sig", newline='\n') as log_file:
	log_file.write('blah blah blah')
	save_file(log_file)
create-selenium-webdriver.py

A helper function that lets you create a new Selenium webdriver object with just one line of code.

from selenium import webdriver
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.firefox.options import Options as FirefoxOptions

def create_webdriver(browser, width, height, is_headless):
    if (browser == 'firefox'):
        firefox_options = FirefoxOptions()
        firefox_options.add_argument('--width={}'.format(width))
        firefox_options.add_argument('--height={}'.format(height))
        if is_headless:
            firefox_options.add_argument('--headless')
        driver = webdriver.Firefox(executable_path = r"..\..\Selenium\geckodriver.exe", options=firefox_options)

    elif (browser == 'chrome'):
        chrome_options = ChromeOptions()
        chrome_options.add_argument('--window-size={},{}'.format(width, height))
        chrome_options.add_experimental_option('excludeSwitches', ['enable-logging']) #Disable JS/browser messages in CMD
        if is_headless:
            chrome_options.add_argument('--headless')
        driver = webdriver.Chrome(executable_path = r"..\..\Selenium\chromedriver.exe", options=chrome_options)

    driver.set_window_size(width, height) #Fallback option; doesn't work in headless mode

    return driver


driver = create_webdriver('chrome', 1200, 900, False)
csv-output.py

Create a comma-delimited CSV file and sanitize its data.

import io
import pathlib
import time

#Sanitize and shrink the given string so that it will fit into a CSV cell
def sanitize_string_for_csv(string):
    if (string == None):
        return '""'
    string = str(string)
    string = string[:32758]
    string = string.replace('"', '""')
    return ('"' + string + '"')


#Convert an array of strings into a valid CSV row string
def generate_csv_row(cells, include_newline):
    if (isinstance(cells, list) == False):
        raise Exception("The first value passed to generate_csv_row must be a list.")
    if (isinstance(include_newline, bool) == False):
        raise Exception("The second value passed to generate_csv_row must be a bool.")
    row_string = ",".join([sanitize_string_for_csv(cell) for cell in cells])
    if (include_newline == True):
        row_string += '\n'
    return row_string


folder_path = 'exports'
file_name = 'foobar-data-' + time.strftime("%b-%d-%Y-%H%M%S").lower() + '.csv'
file_path = folder_path + '/' + file_name

pathlib.Path(folder_path).mkdir(parents=True, exist_ok=True)

with io.open(file_path, 'a', encoding='utf-8-sig', newline='\n') as csv_file:
    csv_file.write(generate_csv_row(['Header 1', 'Header 2'], True))
    csv_file.write(generate_csv_row(['Foo', 'Bar'], True))
    csv_file.write(generate_csv_row(['Lorem', 'Ipsum'], True))
is-selenium-webdriver-alive.py

Check whether the Selenium webdriver object is still alive and connected to its browser process.

from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import WebDriverException

def is_webdriver_alive(driver):
    print('Checking whether the driver is alive')
    try:
        assert(driver.service.process.poll() == None) #Returns an int if dead and None if alive
        driver.service.assert_process_still_running() #Immediately throws a WebDriverException if dead
        driver.find_element_by_tag_name('html') #Throws a NoSuchElementException if dead
        print('The driver appears to be alive')
        return True
    except (NoSuchElementException, WebDriverException, AssertionError):
        print('The driver appears to be dead')
        return False
    except Exception as ex:
        print('Encountered an unexpected exception type ({}) while checking the driver status'.format(type(ex)))
        return False
		

webdriver_status = is_webdriver_alive(driver)

if (webdriver_status == False):
	try:
		driver.quit()
	except:
		pass
	try:
		print('Attempting to create a new webdriver.')
		driver = create_webdriver()
		print('Successfully created a new webdriver.')
	except:
		print('Failed to create a new webdriver.')
main-wrapper.py

Wrap a Python script's main function with an error handler and pause at the end of the script

import os
import time
import traceback

def main():
    do_stuff()
    do_more_stuff()

if (__name__ == "__main__"):
    try:
        os.system('title {}'.format('My Python Program'))
        main()
        input("\nThe script finished successfully. Press the Enter key to exit.")
    except Exception as ex:
        print('The script crashed at ' + time.ctime() + ' due to an unhandled {} exception.'.format(type(ex)))
        print('Full exception text: ' + str(ex))
        print(traceback.format_exc())
        input("\nPress the Enter key to exit.")

This website is owned and operated by SiteBolts. All the code snippets found here are intended to be a starting point and should not be treated as a perfect solution to every problem. We do not guarantee the performance, reliability, or security of the code found on this website. As always, you should ensure that you have adequate backups before adding, changing, or executing any code.