Take the 2-minute tour ×

I am a postdoc and I just finished a cool little scientific application in Python and want to share it with the world. It's a really useful tool for genetecists.

I'd really like to let people run this program through a CGI form interface. Since I'm not a student anymore, I no longer have webspace with a tidy little cgi-bin subdirectory that's hooked up perfectly.

I wrote a simple CGI Python program a few years ago, and was trying to use this as a template.

Here is my quesion: My program needs to create temporary files (when run from the command line it saves images to a given path). I've read a couple tutorials on Apache, etc. and got lots of things running, but I can't figure out how to let my program write temporary files (I also don't know where these files would live, etc.). Any time I try to write to a file (in any manner) in my Python program, the CGI "crashes" and doesn't seem OK.

I am not extremely worried about security because the temporary files will only be outputs of the program (not the user input).

And while I'm asking (I'm assuming you're kind of a CGI ninja if you got this far and weren't bored), do you know my CGI program can take a file argument without making a temporary file?

My previous approach to this was to simply take a list of text as an argument:

    if item.file:
        data = item.file.read()
        if check:
            Tools_file.main(["ExeName", "-d", "-w " + data])
            Tools_file.main(["ExeName", "-s", "-d", "-w " + data])

I'd like to do this the right way! Cheers in advance.

Stack overflowingly yours,

share|improve this question
add comment

2 Answers

up vote 3 down vote accepted

Well, the "right" way is probably to re-work things using an existing web framework like Django. It's probably overkill in this case. Don't underestimate the security aspects here. They're probably more relevant than you think.

All that said, you probably want to use Python's temp file module from the standard library:


It'll generally write stuff out to /tmp/whatever if you're on unix. If your program is crashing only when run under apache (but runs fine when you execute it directly), check your permissions. Make sure your apache user has permission to write to wherever you've decided to store your temp files. Make sure the temp files are written with appropriate permissions (don't want to write a file that you can't read later on).

share|improve this answer
add comment

As Paul McMillan said, use tempfile:

 temp, temp_filename = tempfile.mkstemp(text = True)
 temp_output = os.fdopen(temp, 'w')

My personal opinion is that frameworks are a big time sink unless you really need the prebuilt functionality. CGI is far simpler and can probably work for your application, at least until it gets really popular.

share|improve this answer
add comment

Your Answer


