How many times have you written “
#!/usr/bin/env python” in your life? A few hundred times? :) How to insert this line easily?
I mainly use vim. So far I have done it the following way.
In vim, type this on the first line in normal mode. This is the mode that vim will usually start in, which you can usually get back to with ESC. At the end press ENTER.
!!” brings you to command mode and the current line (which was empty) is replaced with the output of “
which env“. Thus the first line becomes “
/usr/bin/env“. All you need to do is add “
#!” and “
Fine, but I got fed up with this. It’s still too much typing. How to do it easier?
Write a bash script called “py” with the following content:
echo "#!`which env` python"
Put it somewhere in your
PATH and make it executable.
Then, in vim type this on the first line:
Phew. I should have thought of it years ago.
You want to calculate something with Python quickly, from the command line. You might even want to use Python in a bash script to produce some result.
$ python -c "print 2*3" 6
Storing the result in a variable:
$ X=`python -c "print 2*3"` $ echo $X 6
Thanks to Tajti A. for the tip.
You have an interactive Python script that reads input from the command line. You want to add bash-like functionalities to it like moving the cursor with the arrows, jump to the front with Home, jump to the end with End, browse previous commands with the up arrow, etc.
You won’t believe what is needed for this:
Yes, that’s it. Just import it and you are good to go.
import readline while True: inp = raw_input("> ") print "You entered", inp
Before discovering the
readline module, I used to start my scripts with “
It does the trick too. I put the line above in a script called “
my_script.sh” and I launched this latter one. However, “
import readline” is simpler.
You have an interactive script that waits for some user input, similarly to the (Python) shell. In bash, you can use the arrow keys for editing / browsing, but it’s not available in a Python script right away. If you read the user input with
raw_input() for instance, you cannot move the cursor back with the left arrow, or you cannot browse previous commands with the up arrow.
And still… How to add such bash-like functionalities to your script? The method must be absolutely painless, of course.
Use the command “
rlwrap“, which magically adds these functionalities to any script. Awesome. So instead of launching your script with “
./something.py“, launch it like this:
$ rlwrap something.py
You might have to install rlwrap with “
sudo apt-get install rlwrap“. More info about rlwrap: here.
Floating point arithmetic in bash is problematic,
expr supports integers only for instance.
Not an optimal solution but it works:
$ python -c "print 5.5*3" 16.5 $ num=`python -c "print 5.5*3"` $ echo $num 16.5