Having problems outputting proper CGI, Python script? - python

So I am trying to keep my project as simple as possible, therefore I have decided to use a CGI with my Python scripts in order to run a program that does something.
So here is my current setup:
In CMD, I run:
python -m http.server --cgi 8000
This start a server for me. I can access it via localhost:8000.
Next, I am trying to find my directory with the script by typing in the actual address where it is located: localhost:8000/test/cgi-bin/test.py
This is giving me the output of the actual file, not actually reading it properly. I have tried 2 different ways to output data on the Python file, for example:
import sys
sys.stdout.write("Content-type: text\html \r\n\r\n")
sys.stdout.write("<html><title>Hi</title><body><p>This is a test</p></body></html>")
and
print("Content-Type: text/html\n")
print("<!doctype html><title>Hello</title><h2>hello world</h2>")
Both of which result in the actual code being displayed in my browser.
A few questions:
How do I get my server to automatically take me to the location of the file I am trying to run?
How do I get the python script to output the proper stuff?
Am I setting this up correctly?
I am trying to avoid installing any new dependencies and keep it as minimal as possible.
I am running on Python3, Windows7. I am trying to avoid downloading more pip packages and dependencies because my work is very tech precautious.
Any help is greatly appreciated.

First, I want to say that writing plain CGI-scripts in 2017 is a way of a brave person. Your life will be much easier if you would use bottle or flask.
But if you want, here is the way you can start.
python -m http.server --cgi assumes that the cgi-bin is in the current directory. That is you should go to the test directory and start the command from there. And then call http://localhost:8000/cgi-bin/test.py.
Your cgi-script is not correct. The script should be executable. I am not sure if it needs a shebang line in Windows when you run the http.server, but is is required when you run CGI-scripts with Apache web server under Windows. The shebang line starts with #! and then contains the full path to python3 interpreter, and the line should end with \n and not \r\n, otherwise it won't work.
After that you should output all the HTTP-headers, print a blank line, and output your content. All HTTP-headers should be separated by '\r\n' and not '\n'.
Here is an example CGI-script that works on OS X:
#!/usr/bin/env python3
import sys
sys.stdout.write('Status: 200 OK\r\n')
sys.stdout.write('Content-type: text/html;charset="utf-8"\r\n\r\n')
print('<h1>Hello, world!</h1>')

I think the first line of the script needs to specify the interpreter path. Some examples are:
#!/usr/bin/python
#!/usr/bin/python2.3
#!/usr/bin/python2.4
#!c:\Python24\python.exe
#!c:\Python25\python.exe
See if it helps.

According to the http.server documentation:
This defaults to ['/cgi-bin', '/htbin'] and describes directories to treat as containing CGI scripts.
So, http.server is expecting to find CGI scripts in a subfolder named /cgi-bin ot /htbin in your python.exe folder. If you really want to use the test folder, then change the cgi-directories variable in the http/server.py script.

Related

Python Code is not working on Browser

i am new to python and anyhow i managed to install Python on my Linux shared hosting. When I am trying to execute Python code in Shell terminal its working fine but i am not able to execute this code in browser directly and it just shows python code as text.
In Shell: python public_html/index.py (Working)
But if i open same file in browser it doesnt execute code.
index.py
#!/usr/bin/env python
print("Content-Type: text/html\n")
print("Hello World")
I searched everywhere on internet but couldnt find answer, I also installed Django but same problem. please help me :(
I have not done any edit to .htaccess, if here i need any please tell me.
1 new line added in .bashrc
alias python='~/bin/python'
Also I am not sure how my shebang code must look like. Just i saw #!/usr/bin/env python as commonly used SHEBANG code and used in my script.
You have to configure Apache to handle *.py files. Here's a good tutorial:
https://docs.python.org/2/howto/webservers.html
Try hosting your html using CGI server which comes along with python installation
Step 1.(Save the code below in a separate file. Name it START_CGISERVER.py Save it in your working folder)
import SimpleHTTPServer
import SocketServer
import CGIHTTPServer
from CGIHTTPServer import CGIHTTPRequestHandler
from BaseHTTPServer import HTTPServer
server_address=('',8000)
httpd = HTTPServer(server_address, CGIHTTPRequestHandler)
httpd.serve_forever()
Step2 : name your html as index.html (again in your working folder)
Step3 : Run START_CGISERVER.py and let that window open. This means your working folder is hosting as server.
Step 4 : Go to your browser type http://127.0.0.1:8000/
Step 5: Make sure the file which your html is referring to has #!/usr/bin/env python2 as first line, this could be a .py or .cgi file(this will tell CGI interpreter to run your code)

Problems with launch python script from rails

I need to launch a python script with no external dependencies from my rails app. I need to add the folder to PYTHONPATH and start the script. I tried this:
puts system(PYTHONPATH=../lib/python/ python ../reporter/src/reporter.py)
but the script does not work. It should create a specific file, but it doesn't. I also tried:
puts system("PYTHONPATH=../lib/python/ | python ../reporter/src/reporter.py")
but I received the following error:
ImportError: No module named...."
It looks as though PYTHONPATH is not set in the second case. What am I doing wrong? How I can start the python script?
Have you tried
system("export PYTHONPATH=../lib/python/ && python ../reporter/src/reporter.py")
You may also need to put the full path in and use Rails.root.to_s

Use Python on MAMP

I'm slowly migrating from PHP to Python. In particular, as I work in webdev/webdesign I would like to display a basic HTML page using Python, using the following code:
#!/usr/bin/python
print('<html><head></head><body>This is a test</body></html>')
Sending the file online on my host as index.cgi, I've had no problem displaying the content of the file.
The problems start when I try to install the WSGI module on MAMP, or just to make Python work in general with it.
When it go to localhost/index.cgi the content of the file is displayed instead of its results.
I've followed half a dozen tutorials and none seems to work, I always encounter a problem at one point or another. It seems to come from the fact that Apache that comes with MAMP isn't built in a way that lets you add modules to it (such as wsgi).
This is also comes from the fact that I can't find any recent article on how to install Python on MAMP, they all either date from 2008 or 2009, with old versions of MAMP, Python and Macports.
Can somebody points me to the current procedure to make this work ?
EDIT : Ok after finding this article I gathered that MAMP by default don't process CGI scripts outside of the cgi-bin/ folder in MAMP/. So I modified the Apache conf file as explained, it now apparently reads the .cgi file but throws an error 500 with the content shown above. Is the code the culprit or is it MAMP's ?
Got it to work, the problem were the missing CGI interpretation of MAMP outside of the cgi-bin/ folder (see original post) and the missing headers :
print 'Content-type: text/html\n\n'
I've just gone through this process on OSX Catalina with Mamp V5.5
For me I had to follow the following steps:
Make sure your file has the first line:
#!/usr/bin/python
or a path to any valid Python installation or environment. Make sure your python is working correctly.
The file must have the extension cgi e.g.
blah.cgi (not .py)
Then it will work from any folder.
The file must have execute permissions. In terminal:
chmod 755 blah.cgi
The file must send a content type near the beginning ( no brackets for Python versions < 3 ):
print('Content-type: text/html \n\n')
An additional step I would recommend is adding this at the beginning of your page:
import sys
sys.stderr = open("err.log",'w')
Which will route all your error messages to the file err.log in the same directory which is insanely useful for debugging. If your page comes back with 500 Internal Server Error, you should see some errors in err.log file (unless the problem was in initial imports before this statement).
There are other config changes you can make to keep the .py extension but I won't go into that here.
This is just standard CGI, nothing special here, no need for WSGI. You do need to install Python. You can install it wherever you like, as long as your script can find it. You see the line:
#! /usr/bin/python
that is where the script will try to find Python, so change it to your Python installation, or fix your Python installation to be there.

How do I run code from a different directory with a bash script

I have been putting my code on github, but I've run into an implementation snag. I run the same code on many computers (including a computer that I do not have root access on).
One piece of code (a bash script) calls some python code like:
python somecode.py
The shell will run the correct version of python, but it won't find somecode.py.
What I've tried:
Fail #1: I tried to add both the directory which contains somecode.py and the full path to the file to the PATH; to no avail. [Errno 2] No such file or directory
Fail #2: I can make it work for one computer ONLY if I add the full path to the correct version of python in the top line:
#!/usr/local/cool/python/version/location
However this breaks it running on any other computer.
Fail #3: I can also make it work if I make the bash script say:
python /full/path/to/github/place/somecode.py
but again, this only works for ONE computer because the paths are different for different computers.
What I really want to do: I want to be able to use the same code (both bash script and somecode.py) on multiple computers.
Any suggestions about how to do this properly is welcome. Thanks!
Solution
Added:
#!/usr/bin/env python
To the top of my somecode.py code;
mv somecode.py somecode
chmod +x somecode
Make sure PATH has /full/path/to/directory/with/somecode.
Bash script now says only:
somecode
and it works.
For problem #2 try
#!/usr/bin/env python
though it may find different versions of Python on different machines, but as long as that's not a problem this should fix that particular problem
See this SO question Python deployment and /usr/bin/env portability too. And this post by Alex Martelli re use of this.
If you say python somefile.py then it will take the location of somefile.py as the current directory, not from $PATH. It will take the location of python from $PATH.
If you say somefile.py then it will take the location of somefile.py from $PATH, and the location of python from the #! line of your python script, which can use the PATH if you follow #Levon's suggestion.

Running a .py file on LAMP (CentOS) server - from a PHP developer's perspective

I'm a LAMP developer trying out Python for the first time.. I'm okay with picking up the syntax, but I can't figure out how to run it on the server! I've tried the following
uploading filename.py to a regular web/public directory. chmod 777, 711, 733, 773... (variations of execute)
putting the filename.py in cgi-bin, chmod same as above..
Typing up example.com/filename.py simply loads a textfile - nothing appears to have been compiled/parsed/etc!
(I believe python is installed, as
whereis python on my server shows /usr/bin/python among several other directories)
Many words for a simple question - how do you run a python file on a CentOS server?
This is a big mental shift from PHP. Python files are not simply interpreted like .php files[1]. The simplest way I have found to get up & running with Python is the Bottle framework.
I recommend you spend a short while reading http://docs.python.org/howto/webservers.html. It's very informative.
[1]: Note: there is such a thing as Python Server Pages, but it's not widely used.
you can use cgi, but that will not have great performance as it starts a new process for each request.
More efficient alternatives are to use fastcgi or wsgi
A third option is to run a mini Python webserver and proxy the requests from apache using rewrite rules
I agree with the other comments that there may be more efficient ways to run a Python script. Here are some things to try if you'd just like to run a Python script by dropping it into the cgi-bin directory. You'll first want to locate your httpd.conf file. One way to do this is:
locate httpd.conf
Your httpd.conf file is probably located at /etc/httpd/conf/httpd.conf for CentOS. Edit the file and make sure Python files are recognized, especially if you will use them outside of the ScriptedAliased directories:
AddHandler cgi-script .cgi .py
Restart your Apache web-server:
apachectl restart
Create the following test.py file inside the /var/www/cgi-bin directory (default for CentOS):
#! /usr/bin/python
print "Content-type: text/html"
print ""
print "Hello, World!"
You'll want to make the file executable with:
chmod 775 test.py
That should be all that you'll need to do. You can now visit http://{your-domain}/cgi-bin/test.py and the resulting "Hello, World!" should appear.

Categories