views:

49

answers:

1

Hi, I have a Python program where the initiation script looks like this:

if __name__ == "__main__":
    main(sys.argv[1:])

To run this, I have to use Shell or Terminal like this:

myscript somefile.xml

The script accepts a file and then does all the rest of the work. Now, I am trying to run this program on a web server.

SO I use a HTML Form to submit the file to this script. In my Python script, I am doing like this:

....
elif req.form.has_key("filename"):
    item=req.form["filename"]
    if item.file:
        req.write("I GO HERE")
        myscript.main(item)
....

As you can see here, I am trying to send the file directly to the "main" function. Is this the right way to do?

I dont get any script error, but the Python script is not producing the expected results.

Any help? Thanks

A: 

Write the uploaded file contents to a temporary file (using tempfile.mkstemp()) and pass the filename of the temporary file into main() wrapped in a list.

For example (untested):

import os
import tempfile    

fd, temp_filename = tempfile.mkstemp()
try:
    with os.fdopen(fd, "wb") as f:
        # Copy file data to temp file
        while True:
            chunk = item.file.read(100000)
            if not chunk: break
            f.write(chunk)

        # Call script's main() function
        myscript.main([temp_filename])
finally:
    os.remove(temp_filename)
Daniel Pryden
Thanks for your reply,But I get an Syntax error here: with os.fdopen(fd, "wb") as f:
ssdesign
What version of Python? You might need to add `from __future__ import with_statement` at the top of the file.
Daniel Pryden