在屏幕会话中启动Python脚本

问题描述 投票:1回答:1

我目前正在使用一个小的bash脚本在Screen会话中启动.py文件并可以使用帮助。

我有这2个文件:

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脚本aka。这一行:

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. 你能想到一个更好的方法来执行一个必须日夜运行的python脚本但是启动和停止并且不会阻止shell吗?
linux bash python-3.x shell gnu-screen
1个回答
1
投票

回答你的问题:

  1. 如果在脚本上设置了正确的用户/组,则根本不需要使用sudo。
$ chmod 644 <user> <group> <script name>
  1. 创建新实例的行看起来不正确,它应该更像:
screen -S foo -d -m /usr/bin/python /home/Developer/Test/test.py

在使用python exec的完整路径时;删除无用的前一行:screen -dmS foo sh

  1. 屏幕绰绰有余,不喜欢这样的任务。

脚本中的其他问题:

  1. 添加一个shebang到python脚本(例如.#!/usr/bin/python
  2. test.sh第20行的错字:应该是$Status,而不是$Staus
  3. 您可能需要在执行脚本之前最初创建test.log(例如.touch test.log
© www.soinside.com 2019 - 2024. All rights reserved.