How to run a http server which serve a specific path?
<p>this is my Python3 project hiearchy:</p>

<pre><code>projet
  \
  script.py
  web
    \
    index.html
</code></pre>

<p>From <code>script.py</code>, I would like to run a http server which serve the content of the <code>web</code> folder.</p>

<p><a href="https://docs.python.org/3/library/http.server.html" rel="nofollow">Here</a> is suggested this code to run a simple http server:</p>

<pre><code>import http.server
import socketserver

PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
httpd = socketserver.TCPServer(("", PORT), Handler)
print("serving at port", PORT)
httpd.serve_forever()
</code></pre>

<p>but this actually serve <code>project</code>, not <code>web</code>. How can I specify the path of the folder I want to serve?</p>

<p><a href="https://docs.python.org/3/library/http.server.html#http.server.SimpleHTTPRequestHandler" rel="nofollow">https://docs.python.org/3/library/http.server.html#http.server.SimpleHTTPRequestHandler</a></p>

<blockquote>
  <p>This class serves files from the current directory and below, directly
  mapping the directory structure to HTTP requests.</p>
</blockquote>

<p>So you just need to change the current directory prior to starting the server - see <a href="https://docs.python.org/3/library/os.html#os.chdir" rel="nofollow"><code>os.chdir</code></a></p>

<p>eg:</p>

<pre><code>import http.server
import socketserver
import os

PORT = 8000

web_dir = os.path.join(os.path.dirname(__file__), 'web')
os.chdir(web_dir)

Handler = http.server.SimpleHTTPRequestHandler
httpd = socketserver.TCPServer(("", PORT), Handler)
print("serving at port", PORT)
httpd.serve_forever()
</code></pre>

python python-3.x simplehttpserver