cs/practical-file/project.py

143 lines
4.1 KiB
Python

#!/usr/bin/env python3
import os
import subprocess
import sys
def find_next_question_number():
current_dir = os.getcwd()
existing_files = [f for f in os.listdir(current_dir) if f.startswith('question_') and f.endswith('.py')]
if not existing_files:
return 1
numbers = []
for filename in existing_files:
try:
num_str = filename.replace('question_', '').replace('.py', '')
numbers.append(int(num_str))
except ValueError:
continue
return max(numbers) + 1 if numbers else 1
def create_question_file(question_text, question_num):
filename = f"question_{question_num:02d}.py"
with open(filename, 'w') as f:
f.write(f"# Question: {question_text}\n\n")
f.write("")
return filename
def wait_for_completion():
input("Press Enter when the question is done: ")
return True
def execute_code_and_capture_output(filename):
try:
result = subprocess.run([sys.executable, filename],
capture_output=True,
text=True,
timeout=30)
output = {
'stdout': result.stdout,
'stderr': result.stderr,
'returncode': result.returncode
}
return output
except subprocess.TimeoutExpired:
return {
'stdout': '',
'stderr': 'Code execution timed out',
'returncode': 1
}
except Exception as e:
return {
'stdout': '',
'stderr': f'Error executing code: {str(e)}',
'returncode': 1
}
def read_code_from_file(filename):
try:
with open(filename, 'r') as f:
lines = f.readlines()
if len(lines) >= 2:
return ''.join(lines[2:])
else:
return ''.join(lines)
except Exception as e:
return f"Error reading file: {str(e)}"
def append_to_master_file(question_text, question_num, code_content):
with open("outputs.txt", "a") as f:
if os.path.getsize("outputs.txt") == 0:
pass
else:
f.write("\n\n")
f.write(f"Question {question_num:02d}: {question_text}\n\n")
f.write("Answer:\n")
f.write(code_content)
def create_output_file(question_text, question_num, filename, code_content, execution_output):
output_filename = f"question_{question_num:02d}_output.txt"
with open(output_filename, 'w') as f:
f.write(f"Question {question_num:02d}:\n")
f.write(f"{question_text}\n\n")
f.write("Answer:\n")
f.write(code_content)
f.write("\n\nOutput:\n")
if execution_output['returncode'] == 0:
if execution_output['stdout']:
f.write(execution_output['stdout'])
else:
f.write("No output")
else:
if execution_output['stderr']:
f.write(execution_output['stderr'])
else:
f.write("Error occurred")
return output_filename
def main():
question = input("Enter your question: ").strip()
if not question:
return
question_num = find_next_question_number()
filename = create_question_file(question, question_num)
wait_for_completion()
code_content = read_code_from_file(filename)
# execution_output = execute_code_and_capture_output(filename)
# create_output_file(question, question_num, filename, code_content, execution_output)
append_to_master_file(question, question_num, code_content)
# if execution_output['returncode'] == 0:
# if execution_output['stdout']:
# print("Output:")
# print(execution_output['stdout'])
# else:
# print("No output")
# else:
# print("Error:")
# if execution_output['stderr']:
# print(execution_output['stderr'])
# else:
# print("Error occurred")
if __name__ == "__main__":
while True:
main()
print("------------------------------------------------\n\n\n\n\n\n")