Miscellaneous projects
Running shell commands in python
Single line shell commands examples:
import subprocess
# example 1
subprocess.run("echo 'hello'", shell=True, check=True, text=True)
# example 2
subprocess.run('cd /tmp; pwd', shell=True)
# example 3
input_text = "Welcome guest"
message = subprocess.run(["echo", input_text], text=True, \
capture_output=True)
print(message.stdout)
Multiline example:
cmd = '''cd /tmp;
pwd;
'''
subprocess.run(cmd, shell=True, check=True, text=True, \
universal_newlines=True, executable='/bin/bash')
A more comprehensive example: Encrypt a folder recursively using openssl
.
src/encrypt_folder_openssl.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Program: Encrypt folder recursively using openssl
Version: 20220105
@author: Pranab Das (GitHub: @pranabdas)
Run: python3 filename.py
"""
import os
import subprocess
import getpass
# ask folder to encrypt
path = input("Please enter the directory/path to encrypt: ")
# Remove any trailing '/'
if (path[-1] == "/"):
path = path[:-1]
# Get absolute path in case relative path is entered
path = os.path.abspath(path)
# New directory name
new_path = path + "_enc"
# check openssl is installed
try:
openssl_version = subprocess.run(["openssl", "version"],
text=True, capture_output=True)
except:
print("openssl not found. Exiting ...")
exit()
# ask and confirm password
passwd = getpass.getpass(prompt="Please enter encryption password: ")
passwd_confirm = getpass.getpass(prompt="Please confirm your password: ")
if (passwd == passwd_confirm):
pass
else:
print("Password mismatch! Exiting ...")
exit()
print("\nPlease wait. Encrypting...")
for root, dirs, files in os.walk(path):
# Create the folder structure
if path in root:
try:
os.mkdir(root.replace(path, new_path))
except FileExistsError:
pass
# encrypt files using openssl
if (files != []):
for file in files:
file_path = root + "/" + file
new_file_path = file_path.replace(path, new_path) + ".enc"
cmd = f'''openssl enc -e -aes-256-cbc \
-salt \
-iter 1000000 \
-md sha512 \
-k {passwd} \
-in {file_path} \
-out {new_file_path}
'''
subprocess.run(cmd, shell=True, check=True, text=True,
universal_newlines=True, executable="/bin/bash")
print("\nDone. Encrypted files are placed under:\n", new_path)
tip
Conversely, you can also include python code in shell script.
Sort dictionary based on keys with order defined in a list
# orbitals are ordered in terms of stability
orbital_list = [
"1s",
"2s",
"2p",
"3s",
"3p",
"4s",
"3d",
"4p",
"5s",
"4d",
"5p",
"6s",
"4f",
"5d",
"6p",
"7s",
"5f",
"6d",
"7p",
"8s",
]
valence_config = [
{
"orbital": "1s",
"max_occ": 2
},
{
"orbital": "2s",
"max_occ": 2
},
{
"orbital": "3s",
"max_occ": 2
},
{
"orbital": "2p",
"max_occ": 6
},
{
"orbital": "3p",
"max_occ": 6
},
{
"orbital": "3d",
"max_occ": 10
}
]
# sorted in-place
valence_config.sort(key=lambda x: orbital_list.index(x["orbital"]))
# print(valence_config)
# [
# {
# 'orbital': '1s',
# 'max_occ': 2
# },
# {
# 'orbital': '2s',
# 'max_occ': 2
# },
# {
# 'orbital': '2p',
# 'max_occ': 6
# },
# {
# 'orbital': '3s',
# 'max_occ': 2
# },
# {
# 'orbital': '3p',
# 'max_occ': 6
# },
# {
# 'orbital': '3d',
# 'max_occ': 10
# }
# ]