gpt4 book ai didi

python - 在 bash 脚本中执行 python

转载 作者:行者123 更新时间:2023-11-28 22:33:07 28 4
gpt4 key购买 nike

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

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com