2

Using python, how would I check if PHP is installed on my server (CentOS 6.4)? Most of the googled resources point in the opposite direction, i.e to check if the python module is installed in PHP.

Is there any way to check if PHP (whatever version) is installed on the server using Python?

EDIT: I have written a bash script which simply calls php -v and that can be called from within python, but is there any other way in Python directly?

6
  • 1
    Unless you want to check for its presence so that you can remove it, I fail to see the point :s
    – ereOn
    Commented Aug 9, 2013 at 6:38
  • @ereOn - The point is, if it exists, the python script installs some relevant php modules, if not, prompts the user to install PHP
    – rahuL
    Commented Aug 9, 2013 at 6:39
  • @FakeRainBrigand - Sorry, edited post
    – rahuL
    Commented Aug 9, 2013 at 6:40
  • i see no problem with calling php -v
    – mnagel
    Commented Aug 9, 2013 at 6:41
  • @i.h4d35: I think you are overthinking this. First establish "how to detect PHP presence" then implement the solution with anything you like (that can be Python, a shell script or anything really).
    – ereOn
    Commented Aug 9, 2013 at 6:42

3 Answers 3

3

You can use subprocess to check if it can execute the command.

import subprocess as sp
def hasPHP():
    try:
        sp.check_call(['php', '-v'])
        return True
    except:
        return False

Then you can call hasPHP() to get either True or False.


Note: while it's usually best to specify an error type, the variety of errors that could come up (different operating systems, etc.) it makes more sense to leave it out.


About the as syntax:

This line:

import subprocess as sp

Basically does this (it's slightly more complicated):

import subprocess
sp = subprocess
del subprocess

In less formal terms, it gives an alias to a long module name.

0
0

How about:

from os import system
php = system('php --version')

if php != 0:
    print 'Missing: PHP'
1
  • does this take care of custom locations? i.e if the user has install php sin some custom location and hasn't created links to /usr/bin or /usr/local/bin
    – rahuL
    Commented Aug 9, 2013 at 6:45
0

If installed, you'll find a php binary /usr/bin/php or /usr/local/bin/php

To check if a path is an existing file:

os.path.isfile(path)

Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

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.