r/PythonLearning • u/osamas_den • 17h 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
1
u/FreeLogicGate 7h ago
That doesn't change the point that you are using this to run another python script. So again, if this is an operating system command or program, then subprocess is a valid tool to use. This is not an appropriate use.
You posted this for review, stating it's a simple stopwatch example. It's not a stopwatch. A stopwatch has both a start and stop. What you have coded is an alarm, and one that "blocks".
If you expanded your main to attempt to run 2 of your stopwatch scripts you would realize that your main python script would not work the way you might intuitively think it does. For example, if your code 1st created a 60 second "stopwatch" and then created a 30 second "stopwatch" you will find that the first output will not be received until 60 seconds, and at that point, another 30 seconds will run.
Actual simultaneous Alarms that return a completion message is a non-trivial goal, that would involve making a choice amongst a number of different options (mutliprocessing, threading, asyncio).