The Python 🐍 command has many different switches.
Here are the 4 switches I use the most:
-c cmd: program passed in as string;-m mod: run library module as a script;-i: inspect interactively after running script; and-q: don't print version and copyright messages on interactive startup.-cThe switch -c runs code directly from the command line.
It doesn't open the REPL, and it is convenient for short, one-off expressions.
The result isn't printed by default, so don't forget your print!
# What is the factorial of 15?
λ python -c "import math; print(math.factorial(15))"
1307674368000
# What is 2 + 2?
λ python -c "print(2 + 2)"
4
-mThe switch -m runs a module as a script.
This will run an installed module's section that is inside if __name__ == "__main__":.
The one I use the most is the module timeit to measure execution time:
λ python -m timeit -s "import math" "math.factorial(15)"
2000000 loops, best of 5: 167 nsec per loop
λ python -m timeit -s "import math" "math.factorial(150)"
200000 loops, best of 5: 1.52 usec per loop
-iThe switch -i stands for Inspect Interactively.
By running your code with -i, after the script is done,
you get a REPL session with the variables and functions from that script.
Useful to play around with functions you just defined.
Suppose this is your file example.py:
x = 3
y = 5
def add(x, y):
return x + y
If you run it with -i, you get to play around with the variables x and y and with the function add:
λ python -i example.py
>>> x
3
>>> y
5
>>> add(x, 10)
13
-qThe switch -q opens the REPL Quietly.
What this means is that it opens the REPL without displaying all the version/platform information.
I use it when recording videos and demoing things.
λ python -q
>>> # This is a standard REPL
This article was generated automatically from this thread I published on Twitter @mathsppblog. Then it was edited lightly.
Get a daily drop of Python knowledge. A short, effective tip to start writing better Python code: more idiomatic, more effective, more efficient, with fewer bugs. Subscribe here.