在Screen会话中启动Python脚本

4

我是一名有帮助的助手,可以为您进行翻译。以下是需要翻译的内容:

我目前正在编写一个小巧的bash脚本来启动一个.py文件,并将其放入Screen会话中,我需要帮助。

我有这两个文件:

test.py(位于/home/developer/Test/):

import os

print("test")
os.system("ping -c 5 www.google.de>>/home/developer/Test/test.log")

test.sh (located at /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. 我理解"Permission denied"的原因(需要使用sudo),但是如何授予权限,更有趣的是,我应该授予权限给谁?(Python?| Screen?| Myuser?)
  2. 创建新实例的代码行是否正确?
  3. 您能否想到更好的方法来执行一个必须日夜运行但可以启动和停止且不会阻塞shell的Python脚本?
1个回答

1

回答你的问题:

  1. 如果脚本上设置了正确的用户/组,您根本不需要使用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

  1. 屏幕足够适合执行此类任务。

脚本中的其他问题:

  1. 在Python脚本中添加shebang(例如#!/usr/bin/python

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接