5

What would be the most platform-independent way of checking whether Python is installed, from R? This question is actually the inverse of Check if R is installed from python.

EDIT:

Sys.which() does not, as far as I have experienced return the path of the Python executable, even though from the Windows command I can directly access python (meaning that the dir of the python executable is added to %PATH% variables?).

9
  • See this Commented Mar 7, 2018 at 10:18
  • @Abhijeetk431 that is to check for R packages, not external software such as Python. Commented Mar 7, 2018 at 10:19
  • 3
    Under what circumstances does Sys.which not work? Commented Mar 7, 2018 at 10:24
  • 1
    This would be a bug in Sys.which if true but somehow I suspect you are overlooking something. Did you add it to the path after you started R? Did you start R from the cmd line and add python to the path from a cmd process that had been started before you added python to the path? If you are able to find an instance where Sys.which does not work yet python is on your path then reboot your machine and see if it is still the case. Also try shell("where python") from the R console. Commented Mar 7, 2018 at 10:32
  • 1
    try system2('python','-v', stdout = 'stdout.txt', stderr = 'stderr.txt') then check the file or just system2('python') Commented Mar 7, 2018 at 10:46

2 Answers 2

0

You can run this:

vv <- system("pyv=\"$(python -V)\" | echo $pyv| grep \"Python\"")
if(vv){
 print("Python is installed")
}

You could also use this if you were trying to determine which version of Python was on a computer:

vv <- system("pyv=\"$(python -V 2>&1)\" | echo $pyv | grep \"2.7\"")
if(vv){
 print("Python 2 is installed")
}

# or 
vv <- system("pyv=\"$(python -V 2>&1)\" | echo $pyv | grep \"3\"")
if(vv){
 print("Python 3 is installed")
}

Sign up to request clarification or add additional context in comments.

Comments

0

A great solution I was just made aware of: combine Sys.which with nzchar.

If python cannot be found, Sys.which returns an emtpy character

Sys.which("python")
# ""

If python is found,

Sys.which("python")                                                                     # python 
# "C:\\...\\Programs\\Python\\Python310\\python.exe"                                                                    python
nzchar("")
# FALSE
nzchar("A")
# TRUE

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.