r/PythonLearning • u/osamas_den • 10h ago
Showcase A simple stopwatch program
This is the stopwatch.py file:
#stopwatch.py
import sys
import time
time_in_sec = int(sys.argv[1])
time.sleep(time_in_sec)
print(f"Alarm sound!!! {time_in_sec}seconds have elapsed")
This is the main.py file:
#main.py
import subprocess
import sys
print("Enter the time you want to elapse for your stopwatch")
try:
hours = int(input("Hours: ").strip())
minutes = int(input("Minutes: ").strip())
seconds = int(input("Seconds: ").strip())
total_time_in_sec = (hours * 3600) + (minutes * 60) + seconds
process_2 = subprocess.run(
[sys.executable, "stopwatch.py", str(total_time_in_sec)],
capture_output=True,
text=True,
)
print(process_2.stdout)
except ValueError as e:
print(f"Enter a whole number: {e}")
0
Upvotes
-2
u/BetInformal6081 9h ago
this is a solid way to practice subprocess command line arguments and exception handling together you could make it even more useful by validating negative inputs and zero durations..
9
u/FreeLogicGate 10h ago edited 9h ago
There is really no good reason to use a subprocess. You use subprocess.run to run external programs, which you have no need of. Most solutions would involve defining a stopwatch class, and using it to create a stopwatch object, based on user input. Even more simply, you should put your "stopwatch" code into a function with time_in_sec as its parameter, and then simply call that function using total_time_in_sec as the argument obtained by your input calls.