python - 在 bash 脚本中执行 python

标签 python bash unix centos webserver

我需要从 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/

相关文章:

php - UNIX_TIMESTAMP() 和 time() 是否相同

Python dataclasses_json : can I store many references to one object?

python - 我的 FB HackerCup 代码对大输入太慢了

python - 将列表项添加到另一个列表中的项的末尾

linux - bash 中的 unix 历史命令 "!$"是什么?

Linux:在没有副本的情况下更改文件所有权?

python - 无论级别设置如何,如何始终将日志消息写入文件

linux - 想要制作一个shell脚本

linux - Bash 路径计算

linux - 未找到 UNIX 中的 _recalloc