Python CGI script - redirect doesn't always work

I'm writing a small CGI script for an assignment (Python 2.4) that takes form data, runs a shell command with it, and then displays one or another version of its own page depending on what it just did. E.g. if you add a comment, it reloads the "item" version of the page rather than the "list of all items" view, incorporating the new comment. There are several places in the program where it's supposed to reload itself. In one place it works and in one place it doesn't and I'm wracking my brain trying to see the difference.

if mode == "change":
    if newcomment != "":
        comment_command = "some shell command \"" + item + "\" " + comment
        os.system(comment_command)
    if rating != "":
        rate_command = "same command \"" + item + "\" " + rating
        os.system(rate_command)
 # this NEVER works!
    print "%s%s" % ("Location:http://blahblah/cgi-bin/myproject.cgi?item=", urllib.quote_plus(item)) 

elif mode == "newitem":
    add_command = "command \"" + newitem + "\""
    result = os.system(add_command)
    retcode = os.WEXITSTATUS(result)
    # redirect depending on results
    if retcode == 1:
        # this one always works!
        print "%s%s" % ("Location:http://blahblah/cgi-bin/myproject.cgi?item=", urllib.quote_plus(newitem))
    else:
        print("Location:http://blahblah/cgi-bin/myproject.cgi")

I hope this is enough of the code. I don't see why it works in one place and not another. I would assume that it's ignoring both redirects and "falling past" the attempt at a redirect, except that the ?item= version does work in one place. Is there something about os.system that I don't understand?


Asked by: Luke897 | Posted: 27-01-2022






Answer 1

If your command os.system print anything, your Location header could be invalid.

  • Ensure that your os.system is not output anything
  • If it should, the Location header should be go Before any data print
  • prefer subprocess module instead of os.system :
    import subprocess;
    subprocess.Popen(command, shell=True).communicate()

Answered by: Vanessa318 | Posted: 28-02-2022



Answer 2

Check and make sure you're really not outputting anything before the location header. If there's anything at all output before that, you're not going actually get the location header to do anything.

Answered by: Fenton144 | Posted: 28-02-2022



Similar questions

c++ - Redirect python script output to grep

There is a python script that builds cocos2dx-project. When it runs it prints out all the warning and error messages. But I want to get only those lines that contain "error". Therefore, I do the following: python ./build_native.py | grep "error" But it still prints everything, not only "error" lines. EDIT: In case you need the content of the script file, yo...


How to redirect python script cmd output to a file?

So I have a python script that outputs text to the console and I need that logged to a file instead, but the script is quite complex and I don't code python, so I would rather not alter it. I want to do this >python script.py arg1 arg2 ... argn > "somefile.txt" But it won't work, and my guess is that python takes > and "somefile.txt" as arguments....


linux - Cannot redirect python script output to infile

I am working on Debian Stable Linux which is otherwise working very well. I have following code in a python script file named "myrev" which works to reverse order of lines of given text file: #! /usr/bin/python3 import sys if len(sys.argv) < 2: print("Usage: myrev infile") sys.exit() try: with open(sys.argv[1], "r") as f: lines = f.read().split("\n") except: print("Unable to...


python - Batch script pipe and redirect to file

There is something with batch scripting and pipes that I"m missing. I want to check that python has the necessary libraries installed and then error out if it does not. using this command to check python -m pip freeze -r ./requirements.txt | findstr "WARNING" by itself it outputs exactly what I need. however, I try to redirect output to a file or a variable like ...


Python + Django page redirect

How do I accomplish a simple redirect (e.g. cflocation in ColdFusion, or header(location:http://) for PHP) in Django?


python - How to Redirect To Same Page on Failed Login

The Django framework easily handles redirecting when a user fails to log in properly. However, this redirection goes to a separate login page. I can set the template to be the same as the page I logged in on, but none of my other objects exist in the new page. For example, I have a front page that shows a bunch of news articles. On the sidebar is a login form. When the user logs in, but fails to authenticate, I wou...


cgi - How to redirect to another page in Python in CGIAr

If I want to redirect the user from a cgi script to a HTML page using core libraries from the following: import cgi Please could someone point me in the right direction. Nothing more. Simply redirect from cgi script to html page. How ever you would do this Python. If you have to physically write out the HTTP Response Headers to achieve this, then I would appreciate any i...


python - redirect prints to log file

Okay. I have completed my first python program.It has around 1000 lines of code. During development I placed plenty of print statements before running a command using os.system() say something like, print "running command",cmd os.system(cmd) Now I have completed the program. I thought about commenting them but redirecting all these unnecessary print (i can't remov...


python - Pylons redirect to 404 error page

What function to I use to redirect to the default 404 error page? Sample code appreciated. Thank you!


python - Error using redirect in pylons

Using Pylons verson 1.0: Working on the FormDemo example from the Pylons book: http://pylonsbook.com/en/1.1/working-with-forms-and-validators.html My controller has the following functions: class FormtestController(BaseController): def form(self): return render('/simplefor...


python - how to redirect to particular url on 404

@error(404) def error404(error): return 'Nothing here, sorry' This is the way to response 404 in bottle framework. But On 404 I want to redirect to particular url say http://abc.com/. Is it possible?


python - how to redirect form after submit

I've a form, where users select the years and gender, then they click on submit. With these values I'm calculating the numbers, drawing some pictures, etc. Everything fine so far. What I would like to do is open these pictures and data into a pdf file, with the help of documentation. The thing is that I'm not able to redire...


python - Django redirect the right way?

I have a similar question to this - Conditional login redirect in Django But I couldn't understand how to achieve the result from answers there. I am relatively new to django. I reused this code from somewhere, which redirects the user to login page. But after login I always get to the start/ho...


python - Check secure OpenID redirect?

The process for openid login for my server redirects to google, for example, then google redirects back to a page with parameters in the parameter string. how do I verify this really came from google?


bash - Redirect command to input of another in Python

I would like to replicate this in python: gvimdiff <(hg cat file.txt) file.txt (hg cat file.txt outputs the most recently committed version of file.txt) I know how to pipe the file to gvimdiff, but it won't accept another file: $ hg cat file.txt | gvimdiff file.txt - Too many edit arguments: "-" Getting to the python part... # hg...


Python + Django page redirect

How do I accomplish a simple redirect (e.g. cflocation in ColdFusion, or header(location:http://) for PHP) in Django?


python - How to pass information using an HTTP redirect (in Django)

I have a view that accepts a form submission and updates a model. After updating the model, I want to redirect to another page, and I want a message such as "Field X successfully updated" to appear on this page. How can I "pass" this message to the other page? HttpResponseRedirect only accepts a URL. I've seen this done bef...


python - Django: Redirect to previous page after login

I'm trying to build a simple website with login functionality very similar to the one here on SO. The user should be able to browse the site as an anonymous user and there will be a login link on every page. When clicking on the login link the user will be taken to the login form. After a successful login the user should be taken back to the page from where he clicked the login link in the first place. I'm guessing that I ...


How to redirect the output of .exe to a file in python?

In a script , I want to run a .exe with some command line parameters as "-a",and then redirect the standard output of the program to a file? How can I implement that?


python - How to Redirect To Same Page on Failed Login

The Django framework easily handles redirecting when a user fails to log in properly. However, this redirection goes to a separate login page. I can set the template to be the same as the page I logged in on, but none of my other objects exist in the new page. For example, I have a front page that shows a bunch of news articles. On the sidebar is a login form. When the user logs in, but fails to authenticate, I wou...


cgi - How to redirect to another page in Python in CGIAr

If I want to redirect the user from a cgi script to a HTML page using core libraries from the following: import cgi Please could someone point me in the right direction. Nothing more. Simply redirect from cgi script to html page. How ever you would do this Python. If you have to physically write out the HTTP Response Headers to achieve this, then I would appreciate any i...


How to redirect stderr in Python? Via Python C API?

This is a combination of my two recent questions: [1] Python instance method in C [2] How to redirect stderr in Python? I would like to log the output of both stdout and stderr from a python script. The thing I want to ask is...


How to redirect stderr in Python?

I would like to log all the output of a Python script. I tried: import sys log = [] class writer(object): def write(self, data): log.append(data) sys.stdout = writer() sys.stderr = writer() Now, if I "print 'something' " it gets logged. But if I make for instance some syntax error, say "print 'something# ", it wont get logged - it will go into the console instead. Ho...


linux - Redirect stderr to stdout on exec-ed process from python?

In a bash script, I can write: exec 2>&1 exec someprog And the stderr output of someprog would be redirected to stdout. Is there any way to do a similar thing using python's os.exec* functions? This doesn't have to be portable, just work on Linux.






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top