简体   繁体   中英

Execute python within bash script

I need to execute the following code from within a shell script. Typically in languages such as node.js I could write node -e "code here" to execute the code. How can I replicate this functionality with Python?

# Python server
python "import SimpleHTTPServer
import SocketServer
PORT = $pythonPort
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()"

I guess you could use a here document .

For example, here's a simple test script:

#!/bin/bash -ex
testnum=$1

if [ -z $testnum ]; then
    testnum=-1.1
fi

python <<EOF
import math
print(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 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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM