Gabriel
Gabriel

Reputation: 42329

Check if R is installed from python

I have a python code that calls many functions and one of those functions needs the R software installed to be able to run properly.

How can I check from within python if R is installed in the system so as to avoid calling that function if it is not?

BTW I'm running a Linux distro (elementary OS, based on Ubuntu 12.04)

Upvotes: 2

Views: 615

Answers (2)

Kijewski
Kijewski

Reputation: 26022

Simply test the outcome of which R:

from subprocess import check_call, CalledProcessError

try:
     check_call(['which', 'R'])
except CalledProcessError:
     print 'Please install R!'
else:
     print 'R is installed!'

This will work on *BSD (including Mac OSX), too.

Upvotes: 2

Padraic Cunningham
Padraic Cunningham

Reputation: 180401

Use dpkg -s with subprocess:

from subprocess import check_output
print check_output(["dpkg", "-s" , "r-base"])

Or which as @kay suggests :

from subprocess import Popen, PIPE
proc = Popen(["which", "R"],stdout=PIPE,stderr=PIPE)
exit_code = proc.wait()
if exit_code == 0:
    print ("Installed")

Using PIPE you won't see /usr/bin/R in the output

Upvotes: 3

Related Questions