You are not logged in.

#1 2009-11-21 00:45:44

viniosity
Member
From: New York, NY
Registered: 2005-01-22
Posts: 404
Website

how to tell if a program is available in python?

I'm messing around with python again and I want to run a command inside my program.  That command relies on a package being installed in linux.

So, how can I do something like

which foo
=> /usr/bin/foo

which bar
=>

And know to use foo instead of bar inside my code?  Both commands in python return

<subprocess.Popen object at 0x15cf210>

(I am using this command in my code):

foo = subprocess.Popen("which " + "foo", shell=True)

Thanks in advance

Offline

#2 2009-11-21 01:15:56

mikesd
Member
From: Australia
Registered: 2008-02-01
Posts: 788
Website

Re: how to tell if a program is available in python?

You can call a function called communicate() on the Popen object. Check section 18.1.3.1 in the python library docs for an example. Note the stdout argument.

Last edited by mikesd (2009-11-21 01:18:50)

Offline

#3 2009-11-22 14:08:51

kowalski
Member
Registered: 2009-05-07
Posts: 82

Re: how to tell if a program is available in python?

Well, if you want to rely on the user's $PATH then you could do this straight forward by using:

import os
a = os.system("which "+PROGRAM_NAME)
if a != 0:
      use/check for fallback program

But note that which only looks in the paths defined in $PATH so it might miss on some.

Last edited by kowalski (2009-11-22 14:10:50)


He who says A doesn't have to say B. He can also recognize that A was false.

Offline

#4 2009-11-22 14:20:57

Xyne
Administrator/PM
Registered: 2008-08-03
Posts: 6,965
Website

Re: how to tell if a program is available in python?


My Arch Linux StuffForum EtiquetteCommunity Ethos - Arch is not for everyone

Offline

#5 2009-11-22 16:25:07

viniosity
Member
From: New York, NY
Registered: 2005-01-22
Posts: 404
Website

Re: how to tell if a program is available in python?

I ended up using:

check_ack = os.popen("which ack-grep")
if len(check_ack.readlines()) == 0:

Imperfect but it got the job done on short notice.

Offline

#6 2009-11-22 17:46:15

BetterLeftUnsaid
Member
From: My Happy Place
Registered: 2007-11-04
Posts: 78

Re: how to tell if a program is available in python?

You could use subprocess' call or returncode stuff for this as well:

import subprocess

# which returns 1 on error / nothing found
if not subprocess.call(["which", "ack-grep"]):
    # ack-grep was found ... do stuff


# Or, if you wanted the return value + output of which:
which = subprocess.Popen(["which", "ack-grep"], stdout=subprocess.PIPE)

# Any stuff output by running the which command
output = which.communicate()[0]

# The returncode of the which command
ret = which.returncode

Last edited by BetterLeftUnsaid (2009-11-22 17:47:36)

Offline

Board footer

Powered by FluxBB