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
🌐
PyPI
pypi.org › project › apache-manager
apache-manager · PyPI
There’s actually a multitude ... ;-). There are two ways to use the apache-manager package: As the command line program apache-manager and as a Python API....
      » pip install apache-manager
    
Published   Feb 29, 2020
Version   2.2
🌐
Stack Overflow
stackoverflow.com › questions › 23089293 › apache-and-python-command-line-arguments
argparse - apache and python command line arguments - Stack Overflow
April 15, 2014 - I am trying to setup up psdash with apache. PSDASH requires commandline variables to be passed to it and I was wondering how this was acheved within apache. Any help would be great Thanks
Top answer
1 of 2
4

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.

2 of 2
1

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/

🌐
docs.python.org
docs.python.org › 3 › howto › webservers.html
Python 3.14 documentation
Download these documents · Welcome! This is the official documentation for Python 3.14.6
🌐
Martin Thoma
martin-thoma.com › execute-python-on-apache2
Execute Python on Apache2 · Martin Thoma
Somewhere in the /etc/apache2/apache2.conf there is a <Directory ...> part. I've added Options ExecCGI and AddHandler cgi-script .py. Now this part looks like this: <Directory /var/www/> Options Indexes FollowSymLinks ExecCGI AddHandler cgi-script .py AllowOverride None Require all granted </Directory> ... #!/usr/bin/env python # -*- coding: UTF-8 -*- print("Content-Type: text/html\n") print("Hello World!
Top answer
1 of 6
20

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.

2 of 6
3

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.

Find elsewhere
🌐
Moonpoint
support.moonpoint.com › languages › python › apache-running-script.php
Running a Python script on an Apache web server
If there is not such a line, you may need to add it and restart Apache, e.g., with apachectl restart. You can have multiple ScriptAlias directories in the VirtualHost section for a site - see the Configuring CGI Scripts section of 1.4 Web Server Configuration from CGI Programming with Perl. E.g.: ScriptAlias /cgi-bin/ "/home/jdoe/public_html/cgi-bin/" ScriptAlias /cgi2 "/home/jdoe/public_html/test/cgi-bin" If you can run a Python script from a command line interface (CLI), aka shell prompt, without errors, e.g., python example.py, but receive the error message below when running the script on an Apache web server, you may need to change the permissions on the script to make it "executable".
🌐
HowtoForge
howtoforge.com › home › how to run python scripts with apache and mod_wsgi on ubuntu 18.04
How to run Python Scripts with Apache and mod_wsgi on Ubuntu 18.04
Before starting, you will need to install some required packages to your system. You can install all of them by running the following command: sudo apt-get install python libexpat1 ...
Top answer
1 of 3
4

Got it to work. Here are the steps that I followed:

  1. In etc/apache2/httpd.conf I uncommented:

    LoadModule cgi_module libexec/apache2/mod_cgi.so

  2. Restarted Apache sudo apachectl restart

  3. List itemAdded a .htaccess file to my directory with the following contents:

    Options ExecCGI AddHandler cgi-script .py Order allow,deny Allow from all

  4. Added #!/usr/bin/env python to the top of my python script

  5. In terminal enabled execution of the python script using: chmod +x widget.py
2 of 3
1

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/

🌐
Centos-webpanel
wiki.centos-webpanel.com › apache-run-python-script
Apache run python script - Control WebPanel Wiki
Install python & python3 and run python scripts with apache on your CentOS WebPanel server.
🌐
Unixmen
unixmen.com › home › frequently asked questions › how to set up python scripting for apache
How to set up Python scripting for Apache | Unixmen
That is where python, php, perl, ruby etc. comes in. As most servers are not written in those languages, an interface is needed for the server and the interpreter to communicate. The Common Gateway Interface is one such interface, which is widely supported. Another option is to install Apache’s mod_python, which puts a python interpreter within the server itself, thus removing the overhead of the interpreters startup time for each request, in lieu of using more memory.
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › using the raspberry pi › troubleshooting
Run python script as cgi under apache2 server[my experience] - Raspberry Pi Forums
sudo a2enmod cgid cd /etc/apache2/mods-enabled sudo ln -s /etc/apache2/mods-available/cgi.load 3. Modify the config file: /etc/apache2/conf-enabled/serve-cgi-bin.conf to enable python code. ... <Directory "usr/lib/cgi-bin"> ... ... AddHandler cgi-script .py # add this line (there is a blank between cgi-script and .py) </Directory> 4.
🌐
Quora
quora.com › How-do-I-run-a-Python-script-in-my-Apache-web-server
How to run a Python script in my Apache web server - Quora
Answer: Can you show your code becuase you are uploading it to CGI-BIN then your python script must look like this : #!/usr/bin/python import cgitb print "Content-type: text/html" print print " " print "" print " " print "Hello." print " "
🌐
Linux.com
linux.com › home › training and tutorials › configuring apache2 to run python scripts
Configuring Apache2 to run Python Scripts - Linux.com
January 14, 2014 - This is meant as a simple writeup to fill a gap in various “HOWTO”‘s that I read when trying to setup my Apache2 server to process python scripts as CGI, though it would apply to any cgi scripts (perl scripts, compiled binaries…).I’ve been developing for years (C, C++, PHP), but had ...
🌐
LinuxConfig
linuxconfig.org › home › how to setup linux apache mysql python server
Install Apache, MySQL, Python on Linux Easily
September 22, 2025 - $ sudo nano /etc/apache2/sites-available/mysite.conf · Change the DocumentRoot setting to where we plan to install your Python website. We are just using mysite as the directory name. ... Create a setting for ServerName and enter your website’s fully qualified domain name. If you don’t have one, leave it as localhost. ... Below these settings, we need to add the following lines.