Write & Execute Python Code On Command Line

Abhay Shukla
2 min readApr 2, 2020

--

Execute python code without opening interpreter in >>>interactive mode.

This is a tiny tutorial on writing short 1–2 (or 3? 4? may be up to 5?) lines of python code, without requiring to start python interpreter in interactive mode or having to write code as script and running it.

An interactive mode is when python does >>> to you.

Why/when is writing and executing code in this manner useful? Mostly, when you are feeling too lazy. It will, perceivably, save 1 second of your life. I don’t know what you’ll do with that feeling, but here we go.

Source: pixabay.com

Goal: Print number of files and directories at a given path

Pretty simple to do in python, right? Assuming you want to do this in the current path (or any path really), it’s just 2 lines of code…

import os
print(len(os.listdir('.')))

For whatever reason, I didn’t want to
a) open python interpreter in >>>interactive mode
b) write this piece of code, execute it and then
c) get out by executing quit() or control + d

So, here is the alternative. Type the following on your shell and it will work just fine.

python - <<-"HEREDOC"
> import os
> print(len(os.listdir('.')))
> HEREDOC

For me the number was 6. What about you? 89076? Okay, thanks!

You owe me a perceivable second now.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Abhay Shukla
Abhay Shukla

Written by Abhay Shukla

Data Science @ Meesho, Ex- Airtel, Swiggy, [24]7.ai https://www.linkedin.com/in/shuklaabhay/ #DataScience #ML #AI #Statistics #Reading #Music #Running

No responses yet

Write a response