How to tell whetehr Python script called as CGI or from command line?

R

rowan

I'm writing a Python script that can either be called as a Cron job or
as a web page (i.e. as a CGI in response to an HTTP request). This is
to process the mailboxes on my web server (to which I don't have
command line access) to remove old messages. How do I find out whether
the script has been called as a Cron job or as a CGI? I need to know
this so I can format the output correctly, e.g. if this is a web
request I need to start the output with "Content-type: text/html\n
\n<html>", to do newlines by "<p>" or "<br>" etc.

Can I just access some header line which will always have a value in a
web request, but which will be None if running from the command line
or as a Cron job, or something similar? How?

Thanks - Rowan
 
S

Steve Holden

I'm writing a Python script that can either be called as a Cron job or
as a web page (i.e. as a CGI in response to an HTTP request). This is
to process the mailboxes on my web server (to which I don't have
command line access) to remove old messages. How do I find out whether
the script has been called as a Cron job or as a CGI? I need to know
this so I can format the output correctly, e.g. if this is a web
request I need to start the output with "Content-type: text/html\n
\n<html>", to do newlines by "<p>" or "<br>" etc.

Can I just access some header line which will always have a value in a
web request, but which will be None if running from the command line
or as a Cron job, or something similar? How?

Thanks - Rowan
The CGI standard requires that the calling server sets several
environment variables, so you could test for the presence of one or more
of those - this is only going to be indicative, though, since any shell
could have the same variables set in its environment.

import os
if "QUERY_STRING" in os.environ:
# CGI script

might work.

regards
Steve
 
R

rowan

import os
if "QUERY_STRING" in os.environ:
# CGI script

might work.

Thanks Steve for this suggestion. I did something similar:
import os
req = os.getenv('REQUEST_URI')
if (not req is None) and len(req) > 0:
web = True

which seemed to work for me.

Rowan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top