user5109957
user5109957

Reputation:

Simple http server in Python 3.5.1 Shell

I am trying to get a simple http server going, using the directory in my code below as the root. This is using Python 3.5.1 Shell:

>>> import os
>>> import http.server
>>> import socketserver
>>> os.chdir('c:/users/owner/desktop/tom/tomsEnyo2.5-May27')
>>> python -m http.server 8000
SyntaxError: invalid syntax
>>> python -m SimpleHTTPServer 8000
SyntaxError: invalid syntax
>>>  

I have looked at a similar topic: How to set up simple HTTP server in Python 3.5 on Windows 10? , but even when I try doing what the answer suggests, I still have the same problem ('invalid syntax').

Upvotes: 1

Views: 7052

Answers (4)

Julien Palard
Julien Palard

Reputation: 11526

You're confusing Python commands and shells command.

import os etc are Python statements (interpreted by Python), python -m http.server 8000 is a shell statement, interpreted by bash, sh or whatever Microsoft use for Windows. You may try something like this to run it in the Python REPL:

import os
from http.server import SimpleHTTPRequestHandler, HTTPServer                                                                                                                                   

os.chdir('c:/users/owner/desktop/tom/tomsEnyo2.5-May27')                                                                                                                                                                                      
server_address = ('', 8000)                                                                                                                                                                    
httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)                                                                                                                                   
httpd.serve_forever()

But the easiest way to do is probably to just run python -m http.server 8000 while being in the right directory in your terminal emulator. Note, on recent versions of Python, the http.server module also accept a --directory or -d option to specify the directory to serve.

Upvotes: 6

Rajkumar Pandi
Rajkumar Pandi

Reputation: 73

import socket
import sys

try:
 HOST = 'Your_ip'
 PORT = 80
 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
 s.bind((HOST, PORT))
 s.listen(10)
 print '[*]Running HTTP on port %s..'%PORT
 while 1:
    conn, addr = s.accept()
    print 'Connected with ' + addr[0] + ':' + str(addr[1])
    data = ""
    while 1:
        request = conn.recv(8000)
        data += request
        if len(data) == 24:
            print data
            req_list = data.split(' ')
            method = req_list[0]
            req_file = req_list[1]
            print 'The Requested file from client: ', req_file
            fileid = req_file.split('?')[0]
            fileid = fileid.lstrip('/')
            print fileid
            if(fileid == 'index.html'): #verifies index.html
                file = open(fileid,'rb')
                response = file.read()
                file.close()
                header ='HTTP/1.1 200 OK\n'
                mimetype = 'text/html'
                header += 'Content-Type: '+str(mimetype)+'\n\n'
            else:
                header = 'HTTP/1.1 404 Not Found\n\n'
                response = '<html><body><h3>Error 404: File not found</h3></body></html>'
            final_response = header.encode('utf-8')
            final_response += response
            conn.send(final_response)
        else:
            continue
    conn.close()

except KeyboardInterrupt as msg:
 sys.exit(0)

An HTTP server(equivalent implementation in Linux) listens on port 80, and can be customized to listen on all different ports. This server parses the GET request and send successful response if index.html file is present, and its unsuccessful if client tries to access other .html file. Alternative to one liner bash web server

Upvotes: 0

tuned
tuned

Reputation: 1125

The idea itself of running a Web server into the Python shell is wrong as a server is a system-level process supposed to run forever. You can try to run it using the subprocess library maybe?

Furthermore, you cannot run python executable into the shell. Once you run the shell, you need to type code line by line, not OS executables. If you wanto to start a server, you need instead to run the python executable from a directory in your OS command-line, using SimpleServer class; that directory will be served through the Web server.

Upvotes: 0

Alexis Clarembeau
Alexis Clarembeau

Reputation: 2964

The problem is that the python -m command is not a python command itself but should be used in the shell ;)

You can use instead:

import http.server

def start_server(port=8000, bind="", cgi=False):
    if cgi==True:
        http.server.test(HandlerClass=http.server.CGIHTTPRequestHandler, port=port, bind=bind)
    else:
        http.server.test(HandlerClass=http.server.SimpleHTTPRequestHandler,port=port,bind=bind)

start_server() #If you want cgi, set cgi to True e.g. start_server(cgi=True)

Or, you can also do:

import http.server
import socketserver

PORT = 8000

Handler = http.server.SimpleHTTPRequestHandler

httpd = socketserver.TCPServer(("", PORT), Handler)

print("serving at port", PORT)
httpd.serve_forever()

Upvotes: 1

Related Questions