在 Screen 会话中启动 Python 脚本

Start a Pythonscript in a Screen session

我目前正在编写一个小 bash 脚本来在 Screen 会话中启动一个 .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

我的问题:

  1. 我了解权限被拒绝案例的原因(与 sudo 一起使用)但是我如何授予权限,更有趣的是,我应该向谁授予权限? (python? | screen? | myuser?)
  2. 创建新实例的行是否正确,其中的脚本 运行 是这样吗?
  3. 你能想出更好的方法来执行 python 脚本吗?该脚本必须 运行 昼夜不停地启动和停止,并且不会阻塞 shell?

回答您的问题:

  1. 如果在脚本中设置了正确的 user/group,则根本不需要使用 sudo。
$ chmod 644 <user> <group> <script name>
  1. 创建新实例的行看起来不正确,应该更像是:
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

  1. 屏幕足以胜任此类任务。

脚本中的其他问题:

  1. 向 python 脚本添加一个 shebang(例如 #!/usr/bin/python

  2. test.sh 第 20 行的错别字:应该是 $Status,而不是 $Staus

  3. 您可能需要在执行脚本之前先创建 test.log(例如 touch test.log