Why use backticks?

Paul Watson pwatson at redlinec.com
Wed May 7 18:16:38 EDT 2003


Backticks in Python do not mean the same thing as they do in Perl.  Your
Perl friend would need to do something like:

$ python
Python 2.1 (#1, Dec  6 2002, 19:28:59) [C] on aix4
Type "copyright", "credits" or "license" for more information.
>>> import os
>>> f = os.popen('ls -al')
>>> x = f.readlines()
>>> for aline in x:
...   print aline.strip()
...
total 16
drwxr-sr-x   2 pwatson  pwatson       512 May  7 16:32 .
drwxr-sr-x   6 pwatson  pwatson       512 May  7 16:18 ..
-rwxr-xr-x   1 pwatson  pwatson        47 May  7 16:32 bt.pl
-rwxr-xr-x   1 pwatson  pwatson       113 May  7 16:33 bt.py

in order to get the output of the 'ls -al' command.  In Perl, your friend
might write:

$x = `ls -al`;
print $x;

$ ./bt.pl
total 16
drwxr-sr-x   2 pwatson  pwatson       512 May  7 16:32 .
drwxr-sr-x   6 pwatson  pwatson       512 May  7 16:18 ..
-rwxr-xr-x   1 pwatson  pwatson        47 May  7 16:32 bt.pl
-rwxr-xr-x   1 pwatson  pwatson       113 May  7 16:33 bt.py

"Iwan van der Kleyn" <none at none.com> wrote in message
news:3eb81743$0$123$e4fe514c at dreader4.news.xs4all.nl...
> I was showing a friend around Python using the Shell. He asked for a few
> Python equivalents of common Perl and VB constructs. The use of
> backticks come up. After showing the use of os.popen I demonstrated
>
>   out = `ls`
>
> but to my surprise it didn't generate the expected SyntaxError but
> rather a NameError. So after some Googling I found that backticks around
> an expression ( `expression`) are equivalent to calling
> repr(expression). Every day a learning moment.
>
> But why this rather obscure use of backticks? Is there any use for them
> except making code harder to read ? :-)
>
> Regards,
>
> Iwan
>






More information about the Python-list mailing list