简体   繁体   English

检查是否从python安装了R

[英]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. 我有一个调用许多函数的python代码,这些函数之一需要安装R软件才能正常运行。

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? 我如何从python内部检查R是否已安装在系统中,以避免未调用该函数?

BTW I'm running a Linux distro (elementary OS, based on Ubuntu 12.04) 顺便说一句,我正在运行一个Linux发行版(基础操作系统,基于Ubuntu 12.04)

Use dpkg -s with subprocess: 在子进程中使用dpkg -s

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

Or which as @kay suggests : 或者, which是@kay提示:

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 使用PIPE您不会在输出中看到/usr/bin/R

Simply test the outcome of which R : 只需测试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. 这也将在* BSD(包括Mac OSX)上运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM