linux - 在 Screen session 中启动 Python 脚本

标签 linux bash python-3.x shell gnu-screen

我目前正在编写一个小 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

我的问题:

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

最佳答案

回答您的问题:

  1. 如果在脚本中设置了正确的用户/组,则根本不需要使用 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. screen 足以胜任此类任务。

脚本中的其他问题:

  1. 在 python 脚本中添加一个 shebang(例如。#!/usr/bin/python)

  2. test.sh 第 20 行的拼写错误:应该是 $Status,而不是 $Staus

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

关于linux - 在 Screen session 中启动 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38934378/

相关文章:

arrays - 在 bash 脚本中导出数组

python - 获取字符串中出现次数最多的第一个字母

python-3.x - Python 3 中 math.log2(x) 的时间复杂度是多少?

linux - 在 linux chrome 应用程序中显示完整路径而不是 ~ 前缀路径

bash - 如何找到传递给 Bash 脚本的参数数量?

php - Apache 日志 : child pid xxxx exit signal Segmentation fault (11)

bash - 并行运行多个命令,并在其中一个失败或全部成功时返回

python - 如何覆盖 python 的 "not in"运算符

linux - 如何在 korn shell (ksh) 中匹配字符串中的 n 个数字和 n 个字母?

c - 将 stdout 和 stderr 重定向到文件中