Practical Usage of Python's sys Module and hashlib for Data Security
Worrking with Command-Line Arguments in Python
The sys module provides access to command-line arguments through the argv list. By default, argv contains a single element - the script name.
Create a script named argument_processor.py:
import sys
for index, arg in enumerate(sys.argv):
print(f"Argument {index}: {arg}")
Execute the script with additional parameters:
python argument_processor.py param1 param2 param3
The output will display the script name followed by all provided arguments.
Program Termination Control
Use sys.exit() to terminate program execution under specific conditions:
import sys
user_input = input("Enter access code: ")
if user_input != 'valid_code':
print("Access denied")
sys.exit(1)
else:
print("Access granted")
Managing Recursion Limits
Python's interpreter stack depth can be configured using sys functions:
import sys
current_limit = sys.getrecursionlimit()
print(f"Current recursion limit: {current_limit}")
# Set new limit (use caution)
new_limit = 3000
sys.setrecursionlimit(new_limit)
print(f"New recursion limit: {sys.getrecursionlimit()}")
Vertion and Platform Detection
Check interpreter version and platform informaiton for compatibility:
import sys
# Version check
if sys.hexversion >= 0x03080000:
print("Python 3.8+ features available")
else:
print("Consider upgrading Python version")
# Platform detection
print(f"Running on: {sys.platform}")
Implementing Cryptographic Hashing with hashlib
Basic SHA-256 Hashing
import hashlib
# Create hash object
hash_processor = hashlib.sha256()
# Add data to hash
hash_processor.update(b'Sample data for hashing')
# Get hexadecimal digest
print(f"Hash result: {hash_processor.hexdigest()}")
Concise Single-Line Hashing
import hashlib
result = hashlib.sha256(b"Complete message in one operation").hexdigest()
print(f"Compact hash: {result}")
Alternative Constructor Method
import hashlib
# Using new() constructor
hash_obj = hashlib.new('sha256', b"initial data")
print(f"Alternative construction: {hash_obj.hexdigest()}")
Hash Object Methods
update(data): Append data to existing hashdigest(): Return binary hash valuehexdigest(): Return hexadecimal string representationcopy(): Create duplicate hash object
Password Hashing with Salt
import hashlib
# Enhanced security with salt
password_hasher = hashlib.md5()
original_password = "user_password"
secret_salt = "unique_salt_value"
combined = original_password + secret_salt
password_hasher.update(combined.encode())
print(f"Salted hash: {password_hasher.hexdigest()}")