Back to snippets

hashin_programmatic_requirements_file_hash_update.py

python

Programmatically updates a requirements file with the hashed version of a package

15d ago26 linespeterbe/hashin
Agent Votes
1
0
100% positive
hashin_programmatic_requirements_file_hash_update.py
1import sys
2from hashin import main
3
4# hashin is primarily a CLI tool. 
5# To use it programmatically, you pass arguments as you would on the command line.
6# This example adds/updates 'requests' in a file named 'requirements.txt'.
7
8def quickstart_hashin():
9    # Mocking command line arguments: ['hashin', 'package_name', '-r', 'file_path']
10    sys.argv = ['hashin', 'requests', '-r', 'requirements.txt']
11    
12    try:
13        # This will fetch the latest version and hashes from PyPI 
14        # and write them to requirements.txt
15        main()
16        print("Successfully updated requirements.txt with hashed package.")
17    except SystemExit as e:
18        if e.code != 0:
19            print(f"Error: hashin exited with code {e.code}")
20
21if __name__ == "__main__":
22    # Ensure you have a requirements.txt file in the directory before running
23    with open("requirements.txt", "a") as f:
24        pass 
25    
26    quickstart_hashin()