[Novalug] Novalug Digest, Vol 65, Issue 88

Michael Henry lug-user at drmikehenry.com
Sat Mar 17 08:17:46 EDT 2012


On 03/16/2012 08:23 PM, Jamie Duncan wrote:
> Might be bending the rules a little, but a few lines of Python does
> the same thing, and is infinitely easier to read:
[...]
> [root at desktop01 ~]# cat ispath
> #!/usr/bin/env python
>
> import sys
>
> if sys.argv[1] in sys.path:
> print "True"
> else:
> print "False"

One easily fixed problem is that the original quiz required the
script to return success or failure, rather than to print "True"
or "False".

But a larger concern is that Python's ``sys.path`` variable does
not mean the same thing as the ``PATH`` environment variable.

Consider::

  $ echo $PATH
 
/home/mike/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games 


Here are just the first couple of entries in my ``sys.path``::

  $ python -c 'import sys; print(sys.path[:3])'
  ['', '/usr/local/lib/python2.7/dist-packages/pycl-0.2.2-py2.7.egg',
'/usr/local/lib/python2.7/dist-packages/findx-0.8.4-py2.7.egg']

``sys.path`` is for Python's own libraries.  It doesn't include
the directories in the ``PATH`` environment variable, e.g.::

  $ python -c 'import sys; print(sys.path)' | grep /bin
  <no output>

Here's one quick attempt in Python[1] that uses ``PATH``::

  $ cat inpath
  #!/usr/bin/env python

  import os
  import sys

  if sys.argv[1] in os.environ['PATH'].split(':'):
      sys.exit(0)
  else:
      sys.exit(1)


  $ if ./inpath /bin; then echo yes; else echo no; fi
  yes
  $ if ./inpath bin; then echo yes; else echo no; fi
  no

Michael Henry

[1]: Jon LaBadie's correctness concerns are ignored here to
match the spirit of the original Python code (i.e., because I'm
lazy).



More information about the Novalug mailing list