Page 1 of 2 12 LastLast
Results 1 to 15 of 17
  1. #1
    Join Date
    Sep 2005
    Location
    India
    Posts
    748

    phpinfo() alternative in Python

    Hi,

    I am hosted on HostGator and need a Python script to test the Python support on my shared account.

    Is there something similar to phpinfo() in Python?

    Thanks,
    Jatinder
    Darsh Web Solutions : Web Design, PHP Development, E-Commerce Solutions

    PHP Tutorials : Tutorials and scripts for beginners

  2. #2
    Join Date
    Jul 2003
    Location
    Kuwait
    Posts
    5,099
    Not sure of one like phpinfo(), but str(request.environ) should come close.
    In order to understand recursion, one must first understand recursion.
    If you feel like it, you can read my blog
    Signal > Noise

  3. #3
    Join Date
    Sep 2005
    Location
    India
    Posts
    748
    I know nothing about Python. Can you give me the full script?
    Darsh Web Solutions : Web Design, PHP Development, E-Commerce Solutions

    PHP Tutorials : Tutorials and scripts for beginners

  4. #4
    Join Date
    Nov 2001
    Location
    Vancouver
    Posts
    2,416
    There is nothing directly comparable to phpinfo() - much of what that function returns is PHP settings related to the web app integration components.

    Here - I cooked this up for you:
    Code:
    #!/usr/local/bin/python
    # Intentionally not using /usr/bin/env python
    # Why: /usr/local/bin is not passed to CGI scripts by a number of OS
    # thus env would be unable to find python.
    """
    $URL$
    $Id$
    
    pyinfo - A quick look at your Python environment.
    """
    import os
    import pkgutil
    import pprint
    import sys
    from cgi import escape
    
    def dl(tuples):
        output = u''
        output += '<dl>\n'
        for title, description in tuples:
            if title:
                output += '  <dt>%s</dt>\n' % escape(title)
            if description:
                output += '  <dt>%s</dt>\n' % escape(description)
        output += '</dl>\n'
        return output
    
    def group(seq):
        """(seq:(item, category)) -> {category:items}
    
        Groups items by supplied category, e.g.:
            group((e, e.tags[0]) for e in journal.get_recent_entries(100))
    
        Lifted from http://aspn.activestate.com/ASPN/Coo.../Recipe/498223
        """
        result = {}
        for item, category in seq:
            result.setdefault(category, []).append(item)
        return result
    
    def get_packages():
        return set([modname for importer, modname, ispkg in
                       pkgutil.walk_packages(onerror=lambda x:x)
                       if ispkg and '.' not in modname])
    
    def format_packages():
        packages = group((pkg, pkg[0].lower()) for pkg in get_packages())
        # convert ('a',['apackage','anotherapackage]) into ('a', 'apackage, anotherapackage')
        packages = [(letter, ', '.join(pkgs)) for letter, pkgs in packages.items()]
        return '<h2>Installed Packages</h2>\n%s' % dl(sorted(packages))
    
    def format_environ(environ):
        return '<h2>Environment</h2>\n%s' % dl(sorted(environ.items()))
    
    def format_python_path():
        # differentiate between eggs and regular paths
        eggs = [p for p in sys.path if p.endswith('.egg')]
        paths = [p for p in sys.path if p not in eggs]
        return dl([('Paths', ',\n'.join(paths)),
                   ('Eggs', ',\n'.join(eggs)),
                  ])
    
    def format_version():
        version, platform = sys.version.split('\n')
        sysname, nodename, release, osversion, machine = os.uname()
        return '<h2>Version</h2>\n%s' % dl([
            ('Python Version', version),
            ('Build Platform', platform),
            ('OS', sysname),
            ('OS Version', osversion),
            ('Machine Type', machine),])
    
    def format():
        output = u''
        output += '<h1>Python Info</h1>\n'
        output += format_version()
        output += format_python_path()
        output += format_environ(os.environ)
        output += format_packages()
        return output
    
    def page(html):
        print "Content-type: text/html"
        print
        print '<html>\n<head><title>%s Python configuration</title></head>' % os.uname()[1]
        print '<body>\n%s</body>\n</html>' % html
    
    if __name__ == '__main__':
        page(format())
    Its setup to be run as CGI but you can run that on the command line if you like just to see that it works. Comment out format_packages() if you don't like the delay as it goes through your system path.
    “Even those who arrange and design shrubberies are under
    considerable economic stress at this period in history.”

  5. #5
    Join Date
    Nov 2001
    Location
    Vancouver
    Posts
    2,416
    While you are at it, you might want to look at pydoc.

    /usr/local/bin/pydoc2.5 -h

    Try it.
    “Even those who arrange and design shrubberies are under
    considerable economic stress at this period in history.”

  6. #6
    Join Date
    Sep 2005
    Location
    India
    Posts
    748
    Thanks for the reply mwatkins. I uploaded the script to my document root and called it from the browser.

    I just get the code of the script back.

    I then uploaded it to cgi-bin directory where it gave me a 500 internal server error.

    How do I run this script?

    I joined HG two years back when they didn't offer Python support and not sure if I have python enabled on my account. But their tech support says that Python is enabled.
    Darsh Web Solutions : Web Design, PHP Development, E-Commerce Solutions

    PHP Tutorials : Tutorials and scripts for beginners

  7. #7
    Join Date
    Jul 2003
    Location
    Kuwait
    Posts
    5,099
    Ask them how its enabled, through cgi or through mod_python (likely through mod_python).

    If I recall correctly, for mod_python you need to setup a section in .htaccess (or httpd.conf) to enable the handler for your scripts; this is a snippet from one of my servers:

    Code:
    <Location /py>
        SetHandler mod_python
        PythonHandler mod_python.publisher
        PythonDebug On
    </Location>
    The Pylons framework (which uses Paste) has a great display that is similar to phpinfo() at the bottom of error pages when debugging is enabled. My python-fu is not that great otherwise I would extrapolate it for you; but it is available from their svn (it is in the middleware.py file). Posting it here to see if mwatkins can extract it out for us, as this is something quite handy.
    In order to understand recursion, one must first understand recursion.
    If you feel like it, you can read my blog
    Signal > Noise

  8. #8
    Join Date
    Nov 2001
    Location
    Vancouver
    Posts
    2,416
    Quote Originally Posted by Jatinder View Post
    I then uploaded it to cgi-bin directory where it gave me a 500 internal server error.
    The script itself uses all standard modules so my guess its a typical CGI issue -- I suspect its a path problem or file ownership and/or permissions issue (don't forget +x!) - you might try which python (does which exist on Linux? I can't remember). And/or check your httpd error log - it will undoubtedly show what is wrong.

    While HG might enable mod_python as well, I would endeavor to make it work as CGI first.

    Re fyrestrtr's comment - Pylons and Turbogears too IIRC have fantastic debugging output - very nice stuff. I'll have a look at their code when I have a few minutes and see if I can't borrow from it. In the meantime I cooked up something cheap and dirty.

    I've never missed phpinfo() -- Unlike PHP you don't tend to need to go peering into Python to see if X,Y, or Z switch was enabled during compilation. Typically during a build the major choices are include threading or not, and pick what flavour of unicode support you want. All additional support is done through userland-installable packages. Typically the Python interpreter on the machine just works, with perhaps a little more futzing about - not too much - to make mod_python or mod_scgi or the like work with your web httpd of choice.

    But proper tracebacks are a big help; some of the frameworks go way beyond mere tracebacks (which were already good and informative) and allow you to examine variables at the time of the exception, all through a web interface. Pretty slick.
    “Even those who arrange and design shrubberies are under
    considerable economic stress at this period in history.”

  9. #9
    Join Date
    May 2002
    Location
    Norway
    Posts
    122
    There is a function in the cgi module that will output some basic information about the environment, not totally unlike phpinfo(). But it will not give any detailed infomration about the Python installation, mwatkins' script looks better for that.

    Code:
    #!/usr/bin/python
    
    import cgi
    
    cgi.test()
    To enable use of .py-files as cgi scripts you need something like
    Code:
    AddHandler cgi-script .py
    in your Apache configuration. You should be able to add that to your .htaccess file.
    Good Web Hosting Info - Information about web hosting

  10. #10
    Join Date
    Nov 2001
    Location
    Vancouver
    Posts
    2,416
    Installing a CGI script - doesn't cover OS specifics:
    http://docs.python.org/lib/node565.html

    Some helpful tips when running into problems:
    http://docs.python.org/lib/node568.html

    Here's an update to the script to fix a typo with the dl() function and add a little CSS, as well as parsing a query string to include or exclude the package scan.

    http://64.21.147.49/examples/cgi/pyinfo.py

    This is just an example of Python and a little CGI... I have to stress that I never use the CGI module; most Python frameworks interact at a much higher level than that.
    “Even those who arrange and design shrubberies are under
    considerable economic stress at this period in history.”

  11. #11
    Join Date
    Sep 2005
    Location
    India
    Posts
    748
    I got this code posted by "fish" working from my CGI bin and public directory. But still no luck with mwatkins's code.

    Code:
    #!/usr/bin/python
    import cgi
    cgi.test()
    I have to stress that I never use the CGI module; most Python frameworks interact at a much higher level than that.
    Can you explain that a little more?
    Darsh Web Solutions : Web Design, PHP Development, E-Commerce Solutions

    PHP Tutorials : Tutorials and scripts for beginners

  12. #12
    Join Date
    Jul 2003
    Location
    Kuwait
    Posts
    5,099
    Can you explain that a little more?
    When doing web development with Python, there are excellent frameworks that take care of these 'administrative' details like sending our appropriate headers for content, parsing query strings and the like.

    PHP does this in the background for you (sending out appropriate headers). A user-agent cannot display any document unless it has appropriate headers. In CGI programming, your code must generate these headers (like the Content-Type header). PHP, does this for you automatically. Once you start programming in 'raw' CGI in Python (or Perl, or C, or any other language) you have to do this for yourself. Frameworks make this task very easy by automating it for you.

    Take the classic 'hello world' example:

    PHP Code:
    <?php
       
    echo 'Hello world!';
    ?>
    When you save this file and browse to it, you get the expected output. However, what PHP really generates is the text, along with headers (which you can inspect with any plugin or by doing a raw request like below):

    Code:
    $ telnet localhost 80
    Trying 127.0.0.1...
    Connected to localhost.
    Escape character is '^]'.
    GET /test.php HTTP1/1.1
    
    HTTP/1.1 200 OK
    Date: Wed, 01 Aug 2007 08:08:47 GMT
    Server: Apache/2.2.3 (Ubuntu) mod_python/3.2.10 Python/2.5.1 PHP/5.2.1
    X-Powered-By: PHP/5.2.1
    Content-Length: 12
    Connection: close
    Content-Type: text/html; charset=UTF-8
    
    hello world!
    You can see above that PHP is generating extra headers (basically a complete HTTP reply to a request) and embedding your code in the body (payload) of the request. Development in CGI puts the burden on the programmer to write the complete response/request cycle, including headers. Frameworks take care of this so you can concentrate on development of the code.


    Most Python frameworks have the following components; each dealing with a different aspect of web development:

    1. A presentation layer (the template engine)
    2. A ORM/middleware layer (the thing that connects to the databases)
    3. A url mapper (something that points URLs to specific code)

    Examples:

    1. There are many template engines but the most popular ones are Myghty, Mako, Genshi, Kid (used by TurboGears) and Cheetah. In PHP an example would be Smarty.

    2. The two main ones are SQLAlchemy and SQLObject. There really aren't robust ORM layers in PHP, but Creole is one that I have experience with, and others include PEAR::MDB2 and PDO.

    3. Routes is the only one I really know of in this space. I don't know of many in PHP (honestly, before jumping into Python development, I wasn't aware of this concept of routes) -- symfony has something similar to a URL mapper which is XML based.

    There are other things in Python web development that make life easy; but as I am myself trying to understand all the tools and libraries, I cannot speak with authority on the subject. Bottom line is, you have to think a bit differently once you start web development in Python; so it takes a bit of getting used to if you are a PHP programmer.
    Last edited by Burhan; 08-01-2007 at 04:45 AM.
    In order to understand recursion, one must first understand recursion.
    If you feel like it, you can read my blog
    Signal > Noise

  13. #13
    Join Date
    May 2002
    Location
    Norway
    Posts
    122
    Quote Originally Posted by Jatinder View Post
    I got this code posted by "fish" working from my CGI bin and public directory. But still no luck with mwatkins's code.
    It might be the different shebang-line (#!usr/bin/...). Check your error logs for any signs of what is going wrong. You can also add
    Code:
    import cgitb
    cgitb.enable()
    to your scripts (just after the shebang line) to get error messages printed to the screen (doesn't work in all cases). Just be careful to not use this on production sites(passwords etc. in your code might be shown to unlucky visitors).
    Good Web Hosting Info - Information about web hosting

  14. #14
    Join Date
    Sep 2005
    Location
    India
    Posts
    748
    Thanks for the explanation fyrestrstr. I knew about CGI and headers, but wasn't aware of how Python worked and how it is different from PHP.

    I just can't shake the PHP mindset

    I guess it will take me sometime to pick up Python.
    Darsh Web Solutions : Web Design, PHP Development, E-Commerce Solutions

    PHP Tutorials : Tutorials and scripts for beginners

  15. #15
    Join Date
    Nov 2001
    Location
    Vancouver
    Posts
    2,416
    Quote Originally Posted by Jatinder View Post
    I just can't shake the PHP mindset
    I can appreciate that; when I first started looking at Python it was not for a web project but it appealed to me so much I had to figure out how to use it for the web ... wasn't nearly as easy back then as it is now.

    If you just remember that out of the box, PHP has a web framework built in, and Python doesn't, that goes a long way to explaining that you need to either a) build your own framework (that "page" function I wrote in the script above is a mini framework in a manner of speaking) or b) adopt someone else's. I'd opt for what's behind box B if I were you and start down the road with one of the popular Python frameworks.

    If your development platform is *nix, then you have a big selection to pick from and already have the skills to get a platform installed and minimally functional.

    If your development platform is Windows, I think your best bet is to adopt the framework with the largest overall community (Django seems to be the leader here) and start there. Here's a couple of links to get you to "hello, world":

    Note -- I think using sqlite to make it simple would be the way to go initially - Django, and virtually all common Python frameworks, comes with its own built-in web server so with sqlite in development mode you don't have to install any other "server" processes, which makes things easy. sqlite is supported natively in Python these days.

    Django docs themselves:
    http://www.djangoproject.com/documentation/install/

    A quick sampling from around the web:

    Django / sqlite:
    http://ymasuda.jp/python/djhttp://ym...llation_e.html

    Django / Postgresql:
    http://thinkhole.org/wp/django-on-windows/

    Using exemaker:
    http://effbot.org/zone/django.htm
    “Even those who arrange and design shrubberies are under
    considerable economic stress at this period in history.”

Page 1 of 2 12 LastLast

Related Posts from theWHIR.com

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •