Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the current directory when running a SimpleHTTPServer

Tags:

python

Is there any way to set the directory where you want to start a SimpleHTTPServer or BaseHTTPServer?

like image 361
Eldelshell Avatar asked Mar 18 '10 11:03

Eldelshell


People also ask

How do I get the current working directory in python?

To find the current working directory in Python, use os. getcwd() , and to change the current working directory, use os. chdir(path) .

How do I run SimpleHTTPServer?

cfg to a folder and serve with python -m SimpleHTTPServer . Edit the grub config at boot, and away you go. Share a file to/from a VM - Copy a file to a folder and serve with python -m SimpleHTTPServer . Serve a file on an allowed port of firewall - Copy a file to a folder and serve with python -m SimpleHTTPServer port.

How do I transfer files using SimpleHTTPServer?

Go to the directory with the file you want to share using cd on *nix or MacOS systems or CD for Windows. Start your HTTP server with either python -m SimpleHTTPServer or python3 -m http. server. Open new terminal and type ifconfig on *nix or MacOS or ipconfig on Windows to find your IP address.


3 Answers

If you're using SimpleHTTPServer directly from command line, you can simply use shell features:

pushd /path/you/want/to/serve; python -m SimpleHTTPServer; popd

In Python 3 you have to use:

pushd /path/you/want/to/serve; python -m http.server; popd

The SimpleHTTPServer module has been merged into http.server in Python 3.0

like image 161
nkrkv Avatar answered Sep 30 '22 10:09

nkrkv


Doing it without changing directory on Linux:

bash -c "cd /your/path; python -m SimpleHTTPServer"
like image 44
Naveen Avatar answered Sep 30 '22 08:09

Naveen


You can create a script for this (say microserver.sh), and put this inside

#!/bin/bash

pushd /your/directory/
python -m SimpleHTTPServer 8000 &> /dev/null &
popd

Then, change the permissions:

chmod +x microserver.sh

And execute it:

./microserver.sh

This will avoid printing messages to the console and send the process to the background, so you can continue using the console for other things.

Also, it could be called from other scripts, e.g. it can be added to the ~/.bashrc to start the server upon starting the user session. Just add this at the end of the .bashrc

. ./microserver.sh

like image 35
toto_tico Avatar answered Sep 30 '22 08:09

toto_tico