我目前正在编写一个小 bash 脚本以在 Screen session 中启动一个 .py 文件并且可以使用帮助。
我有这两个文件:
test.py(位于/home/developer/Test/):
import os
print("test")
os.system("ping -c 5 www.google.de>>/home/developer/Test/test.log")
test.sh(位于/home/developer/):
#!/bin/bash
Status="NULL"
if ! screen -list | grep -q "foo";
then
Status="not running"
else
Status="running"
fi
echo "Status: $Status"
read -p "Press [Enter] key to start/stop."
if [[ $Status == "running" ]]
then
screen -S foo -p 0 -X quit
echo "Stopped Executing"
elif [[ $Staus == "not running" ]]
then
screen -dmS foo sh
screen -S foo -X python /home/developer/Test/test.py
echo "Created new Instance"
else
exit 1
fi
在必须启动 python 脚本之前,它一直按预期工作。这一行:
screen -S foo -X python /home/developer/Test/test.py
在我的普通 shell 中运行它时,我得到:
test
sh: 1: cannot create /home/developer/Test/test.log: Permission denied
我的问题:
- 我了解权限被拒绝案例的原因(与 sudo 一起使用)但我如何授予权限,更有趣的是,我应该将权限授予谁? ( python ?| screen ?|我的用户?)
- 创建脚本在其中运行的新实例的行是否正确?
- 你能想出更好的方法来执行 python 脚本吗?它必须日以继夜地运行,但可以启动和停止,并且不会阻塞 shell?
最佳答案
回答您的问题:
- 如果在脚本中设置了正确的用户/组,则根本不需要使用 sudo。
$ chmod 644 <user> <group> <script name>
- 创建新实例的行看起来不正确,它应该更像是:
screen -S foo -d -m /usr/bin/python /home/Developer/Test/test.py
While using full path to the python exec; remove useless preceding line:
screen -dmS foo sh
- screen 足以胜任此类任务。
脚本中的其他问题:
在 python 脚本中添加一个 shebang(例如。
#!/usr/bin/python
)test.sh 第 20 行的拼写错误:应该是
$Status
,而不是$Staus
您可能需要在执行脚本之前先创建 test.log(例如,
touch test.log
)
关于linux - 在 Screen session 中启动 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38934378/