Programs that keep running
Many Python programs are short-lived. They start, do one thing, and stop.
Agent-style systems are different. They often stay alive, react to input over time, and produce output incrementally. This lesson introduces the basic shape of programs that are designed to keep running, which is a prerequisite for building classical agents.
Short-lived scripts and long-running programs
A short-lived script runs from top to bottom and then exits. This is ideal for tasks like generating a single HTML file or transforming a dataset.
A long-running program is designed to remain active. It waits, reacts, and continues executing until some stopping condition is met. From Python’s point of view, the difference is not special syntax, but intent. We structure the program so control does not immediately fall off the end.
Keeping a program running with a loop
The simplest way to keep a program alive is to use a loop that does not immediately terminate. The loop acts as the program’s heartbeat.
Here is a minimal example that keeps running and produces output repeatedly:
while True:
print("Agent is running...")
This code never reaches the end of the file. As long as the process is alive, the loop continues.
Reading input repeatedly
Long-running programs usually react to something. One common source is user input.
We can read input inside the loop so the program responds over time:
while True:
command = input("> ")
print(f"You entered: {command}")
Each iteration waits for input, processes it, and then loops again. This pattern appears frequently in command-driven tools and classical agent loops.
Producing output incrementally
Instead of producing all output at once, a long-running program emits results step by step. Output may be printed to the console, written to a file, or sent elsewhere.
For example, generating pages one at a time:
pages = ["Mercury", "Venus", "Earth"]
for name in pages:
print(f"Generating page for {name}")
In a long-running context, similar output would be spread across multiple loop iterations as new work arrives.
Deciding when to stop
Even long-running programs need a way to exit. This is usually handled explicitly.
One simple approach is to check for a specific input and break out of the loop:
while True:
command = input("> ")
if command == "quit":
break
print("Processing command")
The loop continues until the stopping condition is met, at which point the program ends cleanly.
Conclusion
We have seen how Python programs can be structured to run continuously instead of terminating immediately. By combining loops, repeated input, incremental output, and explicit stopping conditions, we gain the basic control needed for long-running systems. This structure forms the foundation for classical agents that sense, decide, and act over time.