登录时在终端中运行python脚本

2024-10-01 09:36:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个python脚本,其中包含一个无限循环中的菜单。我的目标是在用户登录时在终端中启动脚本并开始与之交互。我创造了一个启动器.sh将在启动时执行并在crontab中注册的文件。但是,系统重新启动时会出现以下错误:

1: START
2: POWEROFF
Please make a choice: Traceback (most recent call last):
  File "menu.py", line 27, in <module>
    main()
  File "menu.py", line 16, in main
    choice = input ("Please make a choice: ")
EOFError: EOF when reading a line

这是我的剧本:

#!/usr/bin/python3
def main():
    while True:
        print("1: START")
        print("2: POWEROFF")
        choice = input ("Please make a choice: ")
        print(choice)
        ... other operations

这是我的启动器.sh文件:

#!/bin/sh
# launcher.sh
cd /home/rao/Desktop/project
sudo python3 menu.py
cd /

和crontab行:

@reboot sh /home/rao/Desktop/project/launcher.sh >> /home/rao/Desktop/project/logs/status.log 2>&1

我哪里出错了?你知道吗


Tags: pyproject脚本homemakemainshline
2条回答

Cron作业是以非交互方式执行的,这就是它无法读取用户输入的原因。它们绝对不是应该与用户交互的地方。你知道吗

因为脚本的目的是与用户交互,所以在没有用户的情况下,不需要在系统启动时运行它。我想你应该在用户登录时运行它。你知道吗

您可以将脚本放入用户的~/.profile中,或者如果您使用的是bash,则将其放入~/.bash_profile~/.bashrc。你知道吗

~/.profile~/.bash_profile的情况下,它将在用户每次登录时执行(只有在使用bash时才执行后者)。你知道吗

.bashrc的情况下,它将在用户每次打开交互终端时执行。你知道吗

查看示例this article了解详细信息:

~/.profile is the place to put stuff that applies to your whole session, such as programs that you want to start when you log in (but not graphical programs, they go into a different file), and environment variable definitions.

当我在启动应用程序中输入以下命令时,它起作用了

x-terminal-emulator -e "python3 /path-to-script/menu.py"

相关问题 更多 >