简体   繁体   中英

Why do I keep getting Error 500 on this simple Python-CGI when using subprocess.call()?

I try to trigger system call via a Python 2.7 CGI using this simple script:

import subprocess

print 'Content-Type:text/html'
print
print '<!DOCTYPE html>'
print '<html>'
print '<body>'
print '<pre>'

try:
    subprocess.check_call('/bin/ls')
except:
    pass

print '</pre>'
print '</body>'
print '</html>'

The script runs fine in the shell (even when using the Apache user to run it), but I always receive an Error 500 when running the CGI via the web server. I tried setting shell=True but this does not make a difference. The only message I receive in the Apache error log is:

malformed header from script.

Yet, if I uncomment the subprocess call inside the tags, Apache no longer complaints about the headers and I receive the expected result (Status 200, but of course without the system call).

Am I missing something? Do I have configure Apache to allow for system calls from the CGI? Does such configuration have to be made locally (.htaccess) or globally (/etc/apache2/...)? Any advice on how to fix this? Any help is appreciated.

It apparently happens because the subprocess produces output, which is not piped throug the caller's stdout, as it should, but is flushed directly to the output. Thus, in effect, the output of ls ends up as the CGI-header, hence the 500 error.

os.popen worked, because it does the expected stdout piping for you.

But you can also do the same this (preferred) way:

p = subprocess.Popen('/bin/ls')

(Note: the subprocess is now running asynchronously, unlike with your original subprocess.check_call . If you need a synchronous call (eg you need the output of the child...), you could do something like

out, err = p.communicate()
print(out)

etc. to approximate the original synchronous control flow. And don't forget to add stdout=PIPE to the Popen() call then.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM