Check if a command is valid

Steven W. Orr steveo at syslang.net
Wed Jul 14 16:42:04 EDT 2010


On 07/12/10 21:29, quoth Kenny Meyer:
> Hello,
> 
> I have to figure out if a string is callable on a Linux system. I'm
> actually doing this:
> 
>     def is_valid_command(command):
>         retcode = 100 # initialize
>         if command:
>             retcode = subprocess.call(command, shell=True)
>         if retcode is 0:
>             print "Valid command."
>         else:
>             print "Looks not so good..."
> 
>     is_valid_command("ls")
> 
> Never mind the code, because this is not the original.
> The side effect of subprocess.call() is that it *actually* executes
> it, but I just need the return code. What are better ways of doing
> this?

Luke! Use the force!

#! /usr/bin/python

import os
def is_valid_command(command):
    looking_good = False
    for ii in os.environ['PATH'].split(':'):
        if os.access(ii + '/' + command, os.X_OK):
            looking_good = True
            break
    print ["Looks not so good...", "Valid command."][looking_good]

is_valid_command('python')
is_valid_command('pythoon')

This way you don't start up any subprocesses and you are actually doing what
the shell would do for you.

THE ONLY DIFFERENCE is that a persistent bash would hash all of the contents
of what lives in PATH and so might have a slight shot of being faster under
somewhat obscure conditions.

I would strongly encourage you to not execute an arbitrary string to see if it
returns a pretty return code.

is_valid_command('{cd /; rm -rf /}')

Warning:
* It only checks if the command exists in PATH and is executable TO YOU:
* Do not make fun of is_valid_command. It will get angry.
* You might also want to beef it up a la
        pp = ii + '/' + command
        if os.access(pp, (os.X_OK) and not os.stat.isdir(p)):
so you are checking executable files and not directories etc...
* More warnings can be amplified upon over pitchers of beer.

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 261 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20100714/f1d9157c/attachment.sig>


More information about the Python-list mailing list