Execute python within bash script Execute python within bash script unix unix

Execute python within bash script


I guess you could use a here document.

For example, here's a simple test script:

#!/bin/bash -extestnum=$1if [ -z $testnum ]; then    testnum=-1.1fipython <<EOFimport mathprint(math.fabs($testnum))EOF

You could do the same thing by putting your python logic in a separate python script (that takes commandline args) and then just calling it in your shell script. For example:

python test.py $testnum


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 serverpythonPort=8000python -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 serverimport sysimport SimpleHTTPServerimport SocketServerPORT = int(sys.argv[1])print(sys.argv)Handler = SimpleHTTPServer.SimpleHTTPRequestHandlerhttpd = 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']