The open blogging platform. Say no to algorithms and paywalls.

20 Python Command-Line Hacks I Wish I Knew Sooner

I've been using Python for years now, and I have to admit... there are so many command-line tricks I wish I had known earlier.

It would've saved me hours, maybe even days of frustration. 💡

20 Python Command-Line Hacks I Wish I Knew Sooner

Photo by Zach Graves on Unsplash

I'm here to share those key things I've learned because if you're like me, you'll want to avoid wasting time on stuff that could've been so much easier with just a few tricks.

So, here are 20 Python command-line Hacks I wish I knew sooner (and how they can totally level up your Python game 🚀).

**If you are not a medium member, read my article for free **here.

1. Using python -m for Module Shortcuts 🏃‍♂️

I used to run scripts directly or install packages using pip. But one day, I discovered you could call modules directly using python -m. Game changer!

python -m venv myenv
python -m http.server

Why is this important?

This lets you skip installation steps and run things directly! No more switching between environments or worrying about setup.

2. Quickly Start an HTTP Server 🚀

I can't believe how long I relied on heavy server setups when I just needed to test something locally.

You can start an HTTP server in any directory with a single line:

python -m http.server

Boom!

Localhost is ready in seconds. I use this all the time now for quick file sharing or web development testing.

3. Running Python in Interactive Mode (python -i) 🧑‍💻

This is one of the simplest, yet most powerful tricks. Using python -i script.py, you can execute a script and stay in the interactive mode after it finishes.

This allows you to inspect variables, try out methods, or make on-the-fly changes without rerunning the whole script.

4. Piping Output Directly into Files (I Wish I Knew This Sooner) 📄

Instead of doing print() and manually copying outputs, you can redirect the command-line output directly into a file:

python script.py > output.txt

But let's take it a step further.

Suppose you have a Python script that validates a dataset, and you want to save the valid records in one file (valid_data.txt) and errors in another (invalid_data.txt). You can use:

python script.py 1>valid_data.txt 2>invalid_data.txt
  • 1> redirects stdout (standard output) to valid_data.txt.
  • 2> redirects stderr (standard error) to invalid_data.txt.

To append to a file instead of overwriting it, use >>:

python script.py >> output.txt

5. Using argparse to Handle Command-Line Arguments 🎯

I used to hard-code arguments into my scripts.

Then I found argparse, which handles command-line arguments so much better:

python myscript.py --name John --age 25

It made my scripts way more flexible, and I now pass parameters like a pro.

6. Using python -c to Run Simple Commands from the Command Line 📝

Instead of writing an entire script, you can just run simple Python commands from the terminal using python -c:

python -c "print('Hello, World!')"

Super handy when I just need to test something quickly without creating a file.

7. pip freeze for Environment Snapshots 🧊

This was a massive discovery.

Use pip freeze to get a complete list of all installed packages and their versions:

pip freeze > requirements.txt

It's now my go-to move when managing dependencies for projects. You can recreate entire environments in seconds

8. Creating Isolated Environments with venv 🧪

Virtual environments let you keep project dependencies separate. Here's how you can easily create one:

python -m venv myenv
source myenv/bin/activate # On Linux/Mac
myenvScriptsactivate # On Windows

I regret not using this sooner, as it would've saved me from the mess of conflicting libraries.

9. Using time to Track Execution Time ⏱️

Ever wondered how long your script takes to run? I did and time is the command to help measure it:

time python script.py

Now I can optimize my code by keeping track of performance in real-time.

10. Discovering python -O for Optimized Bytecode 💡

Running Python with the -O flag optimizes the bytecode, skipping assertions. It's useful for performance-heavy production environments.

python -O script.py

It's a hidden gem when you want that extra bit of performance boost.

11. Understanding sys.argv for Custom Arguments 🚀

At first, I hardcoded everything. Then I learned how to handle command-line arguments using sys.argv, which lets you pass parameters dynamically:

import sys
print(sys.argv)

No more re-editing scripts just to test different inputs!

12. Using python -tt to Catch Tab Errors 😬

Python's whitespace sensitivity can be frustrating. The -tt option throws errors for mixed tabs and spaces, saving hours of debugging:

python -tt script.py

This one saved me from the most annoying indentation errors!

13. Combining Commands with && 🧑‍🔧

You can chain Python commands together using &&. For example, this runs two Python scripts in a row:

python script1.py && python script2.py

It's a huge time saver when working with multiple scripts or processes.

14. Using grep to Filter Output 🎯

When I've got a lot of output to sift through, I use grep to filter it down:

python script.py | grep 'keyword'

This lets me find exactly what I need, without the clutter of everything else.

15. Debugging with python -m pdb 🕵️‍♂️

I wish I had known this earlier!

pdb is Python's built-in debugger, and you can use it straight from the command line:

python -m pdb script.py

This lets you step through your code, inspect variables, and find bugs like a detective.

16. Running Scripts in the Background with & 🧑‍💻

Sometimes I need to run long processes without keeping the terminal occupied. Adding & at the end of the command runs it in the background:

python script.py &

Now I can keep working while my code does its thing.

17. Finding Documentation with pydoc 📖

Did you know you can access Python documentation right from the command line using pydoc? I didn't!

Just type:

pydoc <module_name>

It's great for quick reference when you're in the zone and don't want to switch to a browser.

18. Knowing python -B to Ignore Bytecode 🧹

To prevent Python from writing .pyc files, use the -B flag:

python -B script.py

I use this in development environments to keep things cleaner.

19. Using pytest for Test Automation 🚀

Testing code used to be a hassle.

But with pytest, you can automate everything and test multiple cases quickly:

pytest tests

This saves me hours of debugging and verifying my code.

20. Finding Python's Version Easily 🐍

This one's super simple, but a good reminder. Just check your Python version with:

python --version

It's helped me keep track of which version I'm using when switching between different environments.

I wish I'd known all these Python command-line tricks from the start. It would have saved me countless hours of frustration and made my coding life way easier.

Now that I've unlocked these gems, I'm flying through my Python work like never before. 🚀

So, what command-line trick have you been using?

Or do you have any you wish you had known earlier too? Share it in the comments let's all learn together!




Continue Learning