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.
Related
During zerphyr rtos installation process i ran into this error https://pastebin.com/8F5A8S8m, which i safely brute-forced by the link given in the next sentence, but now same error but different file. And here is the code from that file https://pastebin.com/EawPKXRG. So, in short, by googling i couldn't find a way to change interpreter that python uses in this particular files.
FYI
which python
gives python 3.11 one
sudo su
nano etc/path
gives also right directory for python 3.11, but somehow these files use python 3.9 which is installed on this mac by default.'
p.s sorry for the grammar and structure, I'm so mentally drained now to write it properly.
Didn't find anything on google
So you need to run those python files in this format
python3.11 your_desired_file_name
So I installed Miniconda using Homebrew and then installed Spyder using Conda. Then I wanted to make the process more "Mac" friendly by creating an application which opens Spyder so I used the solution by topoman which is below the accepted answer in this link:
Ways to invoke python and Spyder on OSX
Everything works more or less fine except I have ran into two issues (the second one isn't really an issue and more of an aesthetic related thing):
I downloaded py files from this GitHub (https://github.com/realpython/python-scripts) just to test that it will open py files. It works for them and I am also able to set Spyder as the default application by using the "SpyderOpener" solution provided by topoman in the above link.
The issue is that when I create a new file in spyder and save it then try to click-open it, it won't. I'm not sure what the difference is and why the "SpyderOpener" does not work on this py file originating from Spyder, but works fine for the ones I downloaded.
I was curious if it is possible to change the display icon for py files that have the default as "SpyderOpener". I did change the icon for the SpyderOpener application but it doesn't work. The icons for the files is just a blank printer sheet.
UPDATE:
I believe I found the issue. It depends on where the file is. When I put it on my desktop, no issue. When I put it in other certain places no issue. Based on experimenting it seems that the opener does not work when the file is within a folder that has a space in the name (e.g. folder name). The minute I change to folder_name or foldername it works fine.
Therefore, is someone able to explain why the opener script breaks down when there is a space at any place in the file path? Can the script be edited to handle this?
Does it boil down to the following stack threads (i.e. I need to apply double quotes somewhere in the script):
Shell Script and spaces in path
https://askubuntu.com/questions/1081512/how-to-pass-a-pathname-with-a-space-in-it-to-cd-inside-of-a-script
This thread also suggests the script shouldn’t use the $# argument unquoted because it will break as soon as you have “spaces or wildcards”:
https://unix.stackexchange.com/questions/41571/what-is-the-difference-between-and
Therefore looking at the script and previous steps you have:
#!/bin/bash
/usr/local/bin/spyder $#
Then the opener script has:
for f in "$#"
do
open /Applications/spyder.app --args $f
done
if [ -z "$f" ]; then
open /Applications/spyder.app --args ~
fi
As for the rest of the script, I assume $f isn’t going to cause problems? Anyways, it seems the issue comes from the initial setup?
Based on this, it should be handled by the above line:
Handle whitespaces in arguments to a bash script
So is it breaking down because of the args?
I have a Python script with the following code:
#! /home/flohosting/PythonTest/PythonTest/bin/python
print()
print("hello world!")
I'm running Python 3.6 on a GoDaddy VPS. The Python 3.6 is a virtual environment. This script works just fine. The problem arises when in Virtual Studio Code I open a new document, copy the code above from the working .py script and then paste it into the new .py script, upload the script, CHMOD to 755, and try to execute. Then I get a 500 Internal Server Error. It makes no sense to me.
I've logged into my SSH with PuTTY and tried to CHMOD a+x file_name.py where "file_name" is the exact filename and it still doesn't work. I can't think of anything else to even check to see why the script works in a file that's been on the server for 2+ months and not in a new script I upload and CHMOD to 755. Thanks for any suggestions.
EDIT: the link to the script working is http://www.dockethound.com/bernard.py
The link to the non-working script is http://www.dockethound.com/hello.py
EDIT 2: I figured something out and it is working though I have no idea why.
When using CuteFTP 9, I upload on "AUTO". I decided to select ASCII and then try uploading again. When I uploaded I got an error that said "This appears to be a binary file you want to upload with ASCII. Are you sure?" So for some reason the file is being saved in a binary format or something that CuteFTP recognizes as a binary format and is uploading it in binary which causes Apache issues when trying to run it. BUT if it's uploaded in forced ASCII mode, the problems are solved.
Jarod
In my situation, using the Auto setting in CuteFTP 9 allowed CuteFTP to determine that the file types with .py were binary files so the files were transferred via binary and not ASCII. Forcing ASCII fixed the problem, then going into TOOLS->Global Options->ASCII types and adding PY to the list fixed the problem.
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 trying to set up Mercurial repositories to be hosted by IIS under Windows Server 2003. Following this post I installed Python 2.5.4.4 and Mercurial 1.3, set up virtual dir, extracted library.zip and created hgwebdir.config.
However, when I trying to open the http://hostname/hg/hgwebdir.cgi I got an error “The specified CGI application misbehaved by not returning a complete set of HTTP headers.” I did all by best:
Checked IIS mappings to both .py and .cgi extensions. I even tried to use FastCGI with no success.
Created “Hello World” in the same dir and checked that it works fine.
Checked read/exec permissions to Python, IIS and repos directories for IUSR, IWAM and NETWORK SERVICE.
Tried to apply two different patches from Mercurial mailing list. Since they both are old I haven't success with it.
INstalled Sysinternals' procmon and checked for filesystem errors during request. I found nothing except lots of Buffer Overflow results in Python process while it loads it's libraries.
Tried to add 'Content-type: text/html' to the script.
One more thing is when I'm requesting inexistent script file (e.g /hg/inexist.cgi) I have the same error. Nothing helped!
Some more things that I needed to fix:
Where the various HOWTOs say to use c:\whatever\Python26\python.exe -u "%s" "%s" instead use c:\whatever\Python26\python.exe -u -O -B "%s" "%s" -O causes it to also look for .pyo files (not just .py or .pyc, which at least in my version weren't present). -B causes it to not attempt to compile .py files that it finds into .pyo files (which fails due to lacking write permissions)
I'd installed Python 2.7. Mercurial 1.6.2's .pyo files were compiled with Python 2.6. This resulted in a magic number error. Uninstalling 2.7 and installing 2.6.5 fixed this. (If you're reading this at some point in the future, this point may no longer be relevant - check the name of the DLL in Mercurial's directory, or TortoiseHg's directory, depending on where you took library.zip from)
hgwebdir.cgi is now just hgweb.cgi - webdir was integrated into it
In my situation, this error caused by line application = hgwebdir('c:\somewhere\hgweb.config') in hgweb.cgi, it should be application = hgweb('c:\somewhere\hgweb.config').
Besides, uncomment line import cgitb; cgitb.enable() in hgweb.cgi will give you more info about the error( and other errors).
P.S. I use Python 2.6.6 and Mercurial 1.7.3 on Windows Server 2003 with IIS 6.0.
In my case, the critical step that fixed it was using:
c:\whatever\Python26\python.exe -u -O -B "%s" "%s
Before that it was not working with the error:
A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred.
c:\hg\hgweb.cgi in ()
13 import cgitb; cgitb.enable()
14
15 from mercurial import demandimport; demandimport.enable()
16 from mercurial.hgweb import hgweb, wsgicgi
17 application = hgweb(config)
mercurial undefined, demandimport undefined
<type 'exceptions.ImportError'>: No module named mercurial
args = ('No module named mercurial',)
Finally I got that "no headers" error returned on any python script error, so I checked script with console interpreter and fixed errors in my config file. And of course I should ask this question at ServerFault instead of StackOverflow - the lack of sleep did the job :)
There's a pretty good post at http://vampirebasic.blogspot.com/2009/06/running-mercurial-on-windows.html that'll get you started, but if you need more detail or to go further than the writer did, I've got a 4 part blog post that covers everything you need to know about getting up and running on IIS, including Active Directory integration, pull/push privileges, customization of the UI:
http://www.endswithsaurus.com/2010/05/setting-up-and-configuring-mercurial-in.html
It's worth a read...