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

Steve Holden sholden at holdenweb.com
Wed Apr 16 15:08:48 EDT 2003


"Robin Munn" <rmunn at pobox.com> wrote ...
> 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.
>

In shell scripting, it's conventional to use the shell variable $$ in
filenames that must be more-or-less unique. Since $$ yields the (?) process
number, no other process is likely to collide with the filename. Your
file-creation dance would then be a little less likely to interfere with
other similar tasks.

regards
--
Steve Holden                                  http://www.holdenweb.com/
How lucky am I?      http://www.google.com/search?q=Steve+Holden&btnI=1
Python Web Programming                 http://pydish.holdenweb.com/pwp/








More information about the Python-list mailing list