Check if a command is valid

Shashwat Anand anand.shashwat at gmail.com
Tue Jul 13 23:38:58 EDT 2010


On Tue, Jul 13, 2010 at 6:59 AM, Kenny Meyer <knny.myer at gmail.com> wrote:

> 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?
>

Check your $PATH. All your system commands lies there. Make a list and save
it. Now just check whether your 'command' lies in the list. However better
is to run the command, but some commands like 'shutdown' won't be good for
this I think.

~l0nwlf
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100714/c9ebf70e/attachment.html>


More information about the Python-list mailing list