do python's nifty indentation rules spell the death of one-liners?

Robin Munn rmunn at pobox.com
Wed Apr 16 15:09:12 EDT 2003


Gerhard Häring <gh at ghaering.de> wrote:
> * Dan Jacobson <jidanni at dman.ddts.net> [2003-04-15 13:59 +0800]:
>> I need to use one liners every day, especially in Makefiles.  I thus
>> need to know how to make any kind of python program into a big long one
>> liner. However, right out of the starting gates I run into
>> $ python -c 'print 2;for i in (1,4):print i'
>>   File "<string>", line 1
>>     print 2;for i in (1,4):print i
>>               ^
>> SyntaxError: invalid syntax
> 
> Try:
> 
> python -c """
> print 2
> for i in (1, 4):
>     print i
> """
> 
> It seems to work under a bash script at least. I once did something with
><<EOF but have since forgotten the little knowledge I had a about shell
> scripting ;-)

If you're in a shell script, you could do:

----- Cut here -----
# ... do some shell script stuff ...
rm temporary_script.py  # Make sure there isn't a symlink lying around
cat >temporary_script.py <<EOF
# Start of Python code
import math
print math.pi
for i in range(5):
    print i
print "All done"
EOF
python temporary_script.py
rm temporary_script.py
# ... more shell script stuff ...
----- Cut here -----

Notice the first "rm temporary_script.py" to make sure someone hasn't
"carelessly" left a symlink lying around pointing to a file like
/etc/passwd that you wouldn't want overwritten. There is still a race
condition here -- if someone manages to create a symlink between the rm
and the cat, you could be in trouble -- but it would be tricky to
exploit, and you could do away with the problem entirely by using random
(and therefore unpredictable) filenames for your temporary files.

This way you clean up the directory after you're done, and you don't
need to have a ton of small scripts lying around; you can consolidate
them all into one big file. This is the approach used by the GNU
autoconf suite -- take a look at the source of configure sometime.

-- 
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838    50FF 2478 CFFB 081A 8338  54F7 845D ACFD 6AFB 6838




More information about the Python-list mailing list