You can use os.chdir to change the current directory of your script to be the same as the directory which contains the source code.
os.chdir(source_location)
Alternately, you could change configure_command to first change directories using cd prior to running configure.
configure_command = 'cd "%s" && %s' % (source_location, configure_command)
Answer from Suever on Stack Overflow
» pip install apache-manager
Videos
What about apache debug mode (-X) ?
apache2 -X -d. -f.htaccess -C"PidFile `mktemp`" -C"Listen 1025"
-C"ErrorLog /dev/stdout" -C"DocumentRoot `pwd`"
to put it in the background once started you may use Ctrl^Z then type "bg"
Using the the FOREGROUND flag, wrapping it up in a shell script:
#!/bin/sh
if [ $# -ne 2 ]; then
echo "$0 <port> <dir>"
exit 10
fi
/usr/sbin/apache2 -DFOREGROUND -d. -f.htaccess -C"PidFile `mktemp`" \
-C"Listen $1" -C"ErrorLog /dev/stdout" -C"DocumentRoot $2" -e debug
call it "pache", chmod +x, then you can run
./pache 1026 /tmp/webroot
http-server is a much better simple http server than pache, it's what I use currently! :)
Use [pache][1]
Install with npm - which comes with node here: http://nodejs.org/
sudo npm install pache -gRun on current dir, port 3000:
pacheOr specify directory and port:
pache site-directory 2000[1]: https://github.com/devinrhode2/pache
One way, not so easy but simple in some way, is to use CGI, as you said. You can find more information on Apache documentation and Python CGI module documentation.
But, basically, you have to set your server to run cgi scripts. This is done by editing httpd.conf or a .htaccess file: For the first option, add or uncomment the follow:
LoadModule cgi_module modules/mod_cgi.so
ScriptAlias /cgi-bin/ /usr/local/apache2/cgi-bin/ # update the second location according to your configuration. It has to be a place where apache is allow to use, otherwise see apache documentation for setting another directory.
Then, you just need to add your python script in the directory that you set above.
Note that the output from your script must be preceded by a mime-type header, as Apache documentation says.
So, a hello world script could be named hello.py and its content could be:
#!/usr/bin/python
print('Content-type: text/html') # the mime-type header.
print() # header must be separated from body by 1 empty line.
print('Hello world')
Than, you can call your script from a browser:
http://localhost/cgi-bin/hello.py
Note that Python has some goodies inside its cgi realted builtin modules. The cgi module will give you a way to handle forms, and cgitb will give you a helpful (but not perfect) way to debug your script. For more on that, read the documentation again.
Finally, using cgi directly to run python scripts gives you a raw way to work with http requests. There is a lot of already done frameworks, like flask and django, that gives you more power easily. You could check that.
mod_python is your other option. They claim to be faster than CGI, about to explore this myself so I may have answers to questions soon.
https://modpython.org/
The first line of httpd.conf: AddHandler cgi-script .cgi .pl is irrelevant, since you're testing python scripts and not perl scripts. And you should define those directives within the location of your python script, and tell apache that it should execute cgi scripts in that location: Options +ExecCGI. This snippet would be a start:
<Directory /path/to/sample.py />
Options +ExecCGI
AddHandler cgi-script .py
</Directory>
Addendum 1:
As per my last comment, try this script. It should spit information about the cgi environment.
#!/usr/bin/python
import cgi
cgi.test()
Addendum 2:
I got your script to work with the above configuration. The problem is that script is written in python2. And the default interpreter apache is invoking to execute the script, is python3 (at least in my case, and chances are this would be the same for you too).
This is a python3 version of the hello world script:
#!/usr/bin/env python
# enable debugging
import cgitb
cgitb.enable()
print("Content-Type: text/plain;charset=utf-8")
print()
print("Hello World!")
Addendum 3:
For the first error, make sure the permission and the ownership of whatever directory and files you're attempting to deploy are properly set. And try adding those directives to httpd.conf:
Order allow,deny
Allow from all
Which will get you this:
<Directory /path/to/sample.py />
Options +ExecCGI
AddHandler cgi-script .py
Order allow,deny
Allow from all
</Directory>
For the second error, unless I am missing something, it looks like apache is invoking python 3 interpreter to execute your script. To rule out this possibility, you might try the following:
ls -al /usr/bin/python*
This will list the python interpreters available on your system. If you have more than one interpreter you'll get something similar to this output:
/usr/bin/python -> python3*
/usr/bin/python2.6*
/usr/bin/python3*
If not, it would be this output:
/usr/bin/python -> python2.6*
/usr/bin/python2.6*
To make sure, this is not the issue you're having, try with this modified sample script:
#!/usr/bin/python2.6
# enable debugging
import cgitb
cgitb.enable()
print "Content-Type: text/plain\r\n\r\n"
print
print "Hello World!"
You'll notice that I explicitly mentioned the version of the interpreter apache should invoke, which is ugly. But for the sake of testing, you can do it. Of course you should map #!/usr/bin/python2.6, to whatever binary you have on your server, and make sure you don't mix python 3 comtipable code with python 2 interpreter and vice versa.
Re: The Exec format error.
I've run in to this myself a couple of times before. I had the exact same (cryptic) error message.
I was developing Python (3) scripts to use via CGI in Notepad++ on my Windows machine, and then uploading them to my Linux server.
After much frustration, I discovered that this issue is related to line endings and you need to convert Windows line endings (\r\n) to UNIX line endings (\n).
In Notepad++ (6.1.5), you can achieve this by going to the Edit menu and selecting the EOL conversion option and then saving the file.
Got it to work. Here are the steps that I followed:
In
etc/apache2/httpd.confI uncommented:LoadModule cgi_module libexec/apache2/mod_cgi.soRestarted Apache
sudo apachectl restartList itemAdded a .htaccess file to my directory with the following contents:
Options ExecCGI AddHandler cgi-script .py Order allow,deny Allow from allAdded
#!/usr/bin/env pythonto the top of my python script- In terminal enabled execution of the python script using:
chmod +x widget.py
Apache/WebSharing
Their is no GUI to toggle Web Sharing on or off in OSX 10.10, which was previously a GUI option in System Preferences way back in 10.7, but fear not Apache is installed ready to be fired up.
This needs to be done in the Terminal which is found at /Applications/Utilities/Terminal
For those not familiar with the Terminal, it really isn’t as intimidating as you may think, once launched you are faced with a command prompt waiting for your commands – just type/paste in a command and hit enter, some commands give you no response – it just means the command is done, other commands give you feedback – lets get to it….
to start it
sudo apachectl start
to stop it
sudo apachectl stop
to restart it
sudo apachectl restart
To find the Apache version
httpd -v
The Apache version that comes in OSX Yosemite is Apache/2.4.10
After starting Apache – test to see if the webserver is working in the browser – http://localhost – you should see the “It Works!” text.
If you don’t get the localhost test, you can try troubleshooting Apache to see if there is anything wrong in its config file by running
apachectl configtest – Important to check configured properly or not
This will give you an indication of what might be wrong.
Document Root
Document root is the location where the files are shared from the file system and is similar to the traditional names of ‘public_html‘ and ‘htdocs‘, OSX has historically had 2 web roots one at a system level and one at a user level – you can set both up or just run with one, the user level one allows multiple accounts to have their own web root whilst the system one is global for all users. It seems there is less effort from Apple in continuing with the user level one but it still can be set up with a couple of extra tweaks in configuration files. It is easier to use the user level one as you don’t have to keep on authenticating as an admin user. System Level Web Root – the default system document root is still found at – http://localhost/ The files are shared in the filing system at –
/Library/WebServer/Documents/
User Level Root
The other web root directory which is missing by default is the ‘~/Sites’ folder in the User account. This takes a bit longer to set up but some users are very accustomed to using it.
You need to make a “Sites” folder at the root level of your account and then it will work. Once you make the Sites folder you will notice that it has a unique icon which is a throwback from a few versions older. Make that folder before you set up the user configuration file described next.
You have to make a few additional tweaks to get the ~/Sites folder back up and running.
Create cgi-bin folder inside Sites folder and make permission cgi-bin as world-writable. If not a+rwx, then the folder is not writable
chmod a+rwx cgi-bin
Add a “username.conf” filed under:
/etc/apache2/users/
If you don’t already have one (very likely), then create one named by the short username of the account with the suffix .conf, its location and permissions/ownership is best tackled by using the Terminal, the text editor ‘nano‘ would be the best tool to deal with this.
Launch Terminal, (Applications/Utilities), and follow the commands below, first one gets you to the right spot, 2nd one cracks open the text editor on the command line (swap ‘username‘ with your account’s shortname, if you don’t know your account shortname type ‘whoami‘ the Terminal prompt):
cd /etc/apache2/users
sudo nano accountname.conf
Then add the content below swapping in your ‘accountname’ in the code below:
<Directory "/Users/accountname/Sites/">
AllowOverride All
Options Indexes MultiViews FollowSymLinks
Require all granted
</Directory>
<Directory "/Users/accountname/Sites/cgi-bin/">
AllowOverride None
Options ExecCGI
AddHandler cgi-script .cgi .pl .tcl .py
Order allow,deny
Allow from all
</Directory>
Uncomment server name and provide the domain name
ServerName localhost:8080
Permissions on the file should be:
-rw-r--r-- 1 root wheel 298 Jun 28 16:47 accountname.conf
If not you need to change…
sudo chmod 644 accountname.conf
Open the main httpd.conf and allow some modules:
sudo nano /etc/apache2/httpd.conf
And make sure these 4 modules are uncommented (the first 2 should be on a clean install):
LoadModule authz_core_module libexec/apache2/mod_authz_core.so
LoadModule authz_host_module libexec/apache2/mod_authz_host.so
LoadModule userdir_module libexec/apache2/mod_userdir.so
LoadModule cgi_module libexec/apache2/mod_cgi.so
LoadModule php7_module libexec/apache2/libphp7.so
Search for Update directory below permissions.
<Directory />
#Options FollowSymLinks
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride All
Require all granted
</Directory>
Search for and replace ScriptAliasMatch with ScriptAlias and replace with our custom Sites/cgi-bin folder path
ScriptAlias "/cgi-bin/" "/Users/accountname/Sites/cgi-bin/"
Search for and replace with our custom folder permission
<Directory "/Users/accountname/Sites/cgi-bin">
AllowOverride All
Options +ExecCGI
Require all granted
AddHandler cgi-script .cgi .py
</Directory>
Search for ‘AddHandler’ and add below handlers
AddHandler cgi-script .cgi
AddHandler cgi-script .py
If above line creates problem then commented it out And also uncomment this configuration file also in httpd.conf
Include /private/etc/apache2/extra/httpd-userdir.conf
Then open another Apache config file and uncomment another file:
sudo nano /etc/apache2/extra/httpd-userdir.conf
And uncomment:
Include /private/etc/apache2/users/*.conf
Restart Apache for the new file to be read:
sudo apachectl restart
Then this user level document root will be viewable at:
http://localhost/~accountname/
You should only see a directory tree like structure if the folder is empty.
Override .htaccess and allow URL Rewrites
If you are going to use the document root at /Library/WebServer/Documents it is a good idea to allow any .htaccess files used to override the default settings – this can be accomplished by editing the httpd.conf file at line 217 and setting the AllowOverride to All and then restart Apache. This is already taken care of at the Sites level webroot by following the previous step.
sudo nano /etc/apache2/httpd.conf
Also whilst here allow URL rewrites so your permalinks look clean not ugly. Uncomment below line in httpd.conf
LoadModule rewrite_module libexec/apache2/mod_rewrite.so
Python
Once we create python file html code in provola.py, make it executable and place it inside ~/Sites/cgi-bin/ folder
sudo chmod +x provola.py
Restart the apache
sudo apachectl restart
Ref link - http://coolestguidesontheplanet.com/get-apache-mysql-php-phpmyadmin-working-osx-10-10-yosemite/
Neither code works (with and without .communicate()).
You should use instead (assuming passwordless sudo for these commands):
import subprocess
subprocess.check_call("sudo service httpd start".split())
The reasons:
subprocessfunctions do not run the shell by default and therefore the string is interpreted as a name of the command: you should use a list to pass multiple command-line arguments on POSIXPopen()starts the command and returns immediately without waiting for it to finish i.e., it may happen before httpd is started. AssumingPopen()call is fixed,.communicate()waits for the child process to terminate and therefore it returns after httpd is started (whether it was successful or not).
There are different reasons for that to happen: 1. the user is in sudoers and configured to not insert password.
- sudo remembers your password for some time (depending on your system configuration), see: https://unix.stackexchange.com/questions/37299/how-does-sudo-remember-you-already-entered-roots-password
does it work in a brand new terminal session?
It sounds like you want your Python script to be the index document?
If your setup already works when you do something like http://localhost/hello.py I would suggest renaming it to index.py (common convention to call an index document "index.something") and then editing your Apache configuration to include index.py inthe DirectoryIndex filenames list.
I'd highly recommend you write your app (however simple) around a framework. It makes everything massively easier, and you don't end up reinventing wheels. I tend to use Django, or CherryPy.
I recommend you give Cherry a look. The homepage details how to make a Hello World application.
Then all you need to do is ProxyPass to it from Apache, or use mod_wsgi and let apache communicate directly with the application.