You can... it's very confusing (at least it is for me) as soon as you get more than... 3 lines, but you can. For instance:
#!/bin/bash
# Python server
pythonPort=8000
python -c "import SimpleHTTPServer;"`
`"import SocketServer;"`
`"PORT = $pythonPort; "`
`"print(PORT); "`
`"Handler = SimpleHTTPServer.SimpleHTTPRequestHandler; "`
`"httpd = SocketServer.TCPServer((\"\", PORT), Handler); "`
`"print(\"serving at port %s\" % PORT); "`
`"httpd.serve_forever()"
The important part is the -c
(to run the text after it as a command passed to the interpreter)
More information here.
I'd put that in a file if possible, though. If you need the ability to make the port configurable, you can use sys.argsv
in your Python code and pass it in the command call as an argument.
For instance, put this in a script:
run_server.py:
#!/usr/bin/env python
# Python server
import sys
import SimpleHTTPServer
import SocketServer
PORT = int(sys.argv[1])
print(sys.argv)
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print("serving at port %s" % PORT)
httpd.serve_forever()
And call it with python ./run_server.py 8000
The content of sys.argv
is a list, where the first item is the script's name, and then the rest are the arguments passed in the call. In this example's case, that would be: ['./run_server.py', '8000']