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)
Related
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.
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.
I've tried searching for why this keeps happening as I think I've seen others mention this problem.
Whenever I run manage.py runserver from the command line, it just opens the manage.py file from the project directory in notepad. If I include python in the beginning of the command, it says that 'python' is not recognized as an internal or external command, operable program or batch file.
I'm using windows now. I was running linux before and it was working fine...I just transferred all the files that I was working on onto windows and that's when this problem started happening.
To reiterate, the only thing that happens when I run the runserver command is that the manage.py file opens in notepad and it contains the following:
#!/usr/bin/env python
from django.core.management import execute_manager
import imp
try:
imp.find_module('settings') # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__)
sys.exit(1)
import settings
if __name__ == "__main__":
execute_manager(settings)
Your file associations are messed up.
For some reason .py files are associated with notepad.
They aren't associated with Python.
If you know something about windows, you can change the file associations.
if you don't know much about windows, delete and reinstall Python. This time, however, allow it to setup the file associations for you.
Open control panel > Control panel home > Default Programs > set Associations
Search for .py
Select python.exe
Worked for me
On windows I right clicked on my manage.py file in the project directory and then selected open with, then chose another app, then python IDLE, then set the check mark at the bottom of the window to always use this app to open .py files and this was resolved for me. Hope it works for others as well!
I would suggest you create a new virtual environment and then reinstall python and django. That should fix the problem.
i got a:
Error response Error code 403. Message: CGI script is not executable
('/cgi-bin/main.pyc'). Error code explanation: 403 = Request
forbidden -- authorization will not help.
while tying to run a compiled python script (.pyc) on a python CGIHTTPServer. normal python scripts (.py) are working fine.
cgi server looks like this:
from BaseHTTPServer import HTTPServer
from CGIHTTPServer import CGIHTTPRequestHandler
class CGIServer(HTTPServer):
def __init__(self, (hostname,port), handler):
HTTPServer.__init__(self, (hostname, port), handler)
srvaddr = ("", 8000)
cgisrv = CGIServer(srvaddr,CGIHTTPRequestHandler)
cgisrv.serve_forever()
is there any possibility to get this working on windows? .pyc files are linked like .py files under windows. even google can't tell me more.
Thanks
.pyc files are compiled Python scripts, meant to be run on their own. I am rather sure that CGIHTTPServer cannot run compiled Python files, only scripts with the .py extension.
Is there any reason you can't use a .py instead?
You need to write a tiny wrapper (in normal python) to load the other code as a module.
For more details, please consider the python tutorial [1] and its comments:
A program doesn't run any faster when it is read from a ".pyc" or
".pyo" file than when it is read from a ".py" file; the only thing
that's faster about ".pyc" or ".pyo" files is the speed with which
they are loaded.
When a script is run by giving its name on the command line, the
bytecode for the script is never written to a ".pyc" or ".pyo" file.
Thus, the startup time of a script may be reduced by moving most of
its code to a module and having a small bootstrap script that imports
that module.
FYI - I just tested CGIHTTPServer with a script and the compiled version
of that same script. I got the error you noted, and when I tried to run
the two versions on the command line, running the .py version printed
the expected output, and running the .pyc version caused a bunch of
garbage to be printed on the terminal (I didn't bother to investigate the
exact source). In summary - double check that you can run a program on
the command line as a basic test.
[1] http://docs.python.org/release/1.5.1p1/tut/node43.html
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.