Skip to content

Instantly share code, notes, and snippets.

@SerJaimeLannister
Created February 15, 2025 10:06
Show Gist options
  • Select an option

  • Save SerJaimeLannister/019b6f05cd5987994dbb44a5987ed56a to your computer and use it in GitHub Desktop.

Select an option

Save SerJaimeLannister/019b6f05cd5987994dbb44a5987ed56a to your computer and use it in GitHub Desktop.
import os
import shutil
import tempfile
import subprocess
import random
import string
import argparse
import time
import datetime
def generate_random_string(length):
characters = string.ascii_letters + string.digits
return ''.join(random.choice(characters) for _ in range(length))
def process_file(file_path):
"""
Copies a file, generates requirements, and runs the file with uv run.
Prints only the target file's stderr on failure.
"""
try:
# 1. Create a random temporary directory
temp_dir_name = generate_random_string(10)
temp_dir = os.path.join(tempfile.gettempdir(), temp_dir_name)
os.makedirs(temp_dir)
# 2. Copy the file to the temp directory
temp_file_path = os.path.join(temp_dir, os.path.basename(file_path))
shutil.copy2(file_path, temp_file_path)
# *** Get the original directory BEFORE changing the working directory ***
original_dir = os.path.dirname(os.path.abspath(file_path))
file_name_without_ext = os.path.splitext(os.path.basename(file_path))[0] # Get filename without extension
# 3. Change the current working directory to the temp directory
os.chdir(temp_dir)
# 4. Run uvx pipreqs (or pipreqs)
try:
subprocess.run(["uvx", "pipreqs", "."], check=True, capture_output=True, text=True)
# OR, if pipreqs is installed directly:
# subprocess.run(["pipreqs", "."], check=True, capture_output=True, text=True)
except subprocess.CalledProcessError as e:
print(f"Error running uvx pipreqs (or pipreqs): {e}")
print(f"Stdout: {e.stdout}")
print(f"Stderr: {e.stderr}")
return False
# 5. Create requirements file with timestamp
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S") # Get current timestamp
requirements_file_name = f"requirements-{file_name_without_ext}-{timestamp}.txt"
temp_requirements_path = os.path.join(temp_dir, "requirements.txt") # pipreqs always creates requirements.txt
if os.path.exists(temp_requirements_path):
original_requirements_path = os.path.join(original_dir, requirements_file_name)
shutil.copy2(temp_requirements_path, original_requirements_path)
else:
print("requirements.txt not found in temp directory.")
return False
# 6. Clean up: Remove the temporary directory
shutil.rmtree(temp_dir)
# 7. Run the file with uv run and the generated requirements file (CORRECTED)
try:
# *** Change back to the original directory before running uv run ***
os.chdir(original_dir) # Go back to the original directory
result = subprocess.run(
["uv", "run", "--with-requirements", original_requirements_path, file_path],
check=False, capture_output=True, text=True
) # check=False
# Print both stdout and stderr to see what the script outputs
if result.returncode != 0: # Check for non-zero return code
print(f"Error occurred: {result.stderr}") # Print only stderr if there is an error
return False # Indicate failure
else:
# Print the standard output if the script ran successfully
print(f"Script output: {result.stdout}")
return True # Indicate success
except Exception as e:
print(f"An error occurred: {e}")
return False # Important: Return False on exception as well
except Exception as e:
print(f"An error occurred while processing the file: {e}")
return False # Indicate failure if any error occurs in the main process
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Process a file, generate requirements, and run it.")
parser.add_argument("file_path", help="Path to the file to process")
args = parser.parse_args()
file_path = args.file_path
if process_file(file_path):
pass
else:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment