我需要从 shell 脚本中执行以下代码。通常,在 Node.js 等语言中,我可以编写 node -e "code here"
来执行代码。如何使用 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()"
最佳答案
我想你可以使用 here document .
例如,这是一个简单的测试脚本:
#!/bin/bash -ex
testnum=$1
if [ -z $testnum ]; then
testnum=-1.1
fi
python <<EOF
import math
print(math.fabs($testnum))
EOF
您可以通过将 python 逻辑放入单独的 python 脚本(需要命令行参数)中,然后在 shell 脚本中调用它来完成相同的操作。例如:
python test.py $testnum
关于python - 在 bash 脚本中执行 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40251109/