Check if a command is valid
Kenny Meyer
knny.myer at gmail.com
Tue Jul 13 18:00:44 EDT 2010
Chris Rebert (clp2 at rebertia.com) wrote:
> On Mon, Jul 12, 2010 at 6:29 PM, 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
>
> "callable" seems vague. Is a command string with invalid arguments but
> a valid executable "callable"? If no, then there's no general way to
> test "callability" without actually running the command.
I'm glad you pointed that out, because you're right. I subconciously
meant a file that is in the $PATH.
[snip]
>
> Well, you're not gonna be able to get the command's return code
> without actually running it (unless perhaps you're referring to a
> return code from the shell itself?).
>
> > What are better ways of doing this?
>
> One idea:
>
> from shlex import split as shell_tokenize
> from subprocess import check_output
>
> def is_valid_command(command):
> try:
> executable = shell_tokenize(command)[0]
> except (ValueError, IndexError):# invalid shell syntax
> return False
> return bool(check_output(['which', executable]))# on the PATH?
>
I have tried this and found some unexpected issues with Python 2.6 which I
though I should point out:
Firstly, the function `check_output` in the `subprocess` module only comes with
Python 2.7, but I have found a similar function called `check_call` [1] which
seems is similar, but not the same.
[1] http://docs.python.org/library/subprocess.html#subprocess.check_call
The code now looks like this:
from shlex import split as shell_tokenize
from subprocess import check_call, CalledProcessError
def is_valid_command(command):
try:
executable = shell_tokenize(command)[0]
check_call(['which', executable]) # Raises CalledProcessError if
# something went wrong
return True
except (ValueError, IndexError, CalledProcessError): # Catch exception if there
# was an error calling the process
return False
The idea with `which` is really great one.
Thanks a lot, for your time and your input.
--
Onward and upwards,
Kenny Meyer
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 198 bytes
Desc: Digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20100713/b4420cc7/attachment-0001.sig>
More information about the Python-list
mailing list