Python is a very powerful language, with just a couple of lines you can make Python behave like a mini bash shell.
It sounded too good so I tried writing those couple of lines and result was a tiny program that lets you run commands like ls
, pwd
or anything else you'd normally run in terminal, all from inside Python.
Full code:
import os
command = input("$ ")
while command != "exit":
os.system(command)
command = input("$ ")
print("Thank you, exiting!")
How it works?
- Python shows me a prompt ($ ) and waits for my input.
- If I type something like ls (on Linux/Mac) or dir (on Windows), it passes that command to os.system().
- Behind the scenes, os.system() calls a C function (system()), which then asks the shell (/bin/sh or cmd.exe) to run the command.
- The shell runs it, prints the output right in my terminal, and then Python asks me again for the next command.
- If I type exit, the loop stops and the script politely says “Thank you, exiting!”
Here's the flow diagram:
So that was it, remember...running raw shell commands is a risky job as someone could just rm -rf *
deleting everything on your computer but it’s a nice way to peek under the hood at how Python talks to the operating system.
Top comments (0)