如何在Ubuntu服务器中运行后台运行Python程序

How to run the Python program in the background in Ubuntu server

我有一个 python 脚本。脚本具有 Chrome 的 selenium 并访问网站,获取数据并放入 CSV 文件。
这是一部很长的作品。
我把脚本放在服务器上。和 运行。所有的工作。 但我需要脚本在后台工作。

chmod +x createdb.py
nohup python ./createdb.py &

我明白了

(env)$ nohup ./createdb.py &
[1] 32257
(env)$ nohup: ignoring input and appending output to 'nohup.out'

按回车键。

(env)$ nohup ./createdb.py &
[1] 32257
(env)$ nohup: ignoring input and appending output to 'nohup.out'
[1]+  Exit 1                  nohup ./createdb.py

然后它 运行s 并立即将错误写入文件,即 Chrome 没有启动或没有点击。
我想提醒你,如果你不使用 nohup 启动,那么一切都会正常。
我究竟做错了什么?如何运行脚本?
非常感谢。

你可以使用 screen 命令,效果很好。

这是一个非常好的link:https://www.rackaid.com/blog/linux-screen-tutorial-and-how-to/

您可以创建后台守护进程(服务)
您标记 Ubuntu 16.04 表示您已安装 systemd,有关如何设置它的更多信息,请访问此 link

创建一个名为 <my_service>.system 的文件 并把它放在那里:/etc/systemd/system

您的 systemd 单元可能如下所示:

[Unit]
Description=my service
After=graphical.target

[Service]
Type=simple
WorkingDirectory=/my_dir
ExecStart=python my_script.py

[Install]
WantedBy=multi-user.target

那么您所要做的就是重新加载 systemd 管理并启动您的服务:

sudo systemctl daemon-reload
sudo systemctl myservice start

您可以使用来自 env 目录的简单命令:

(env)$ python /path/to/createdb.py > logger.txt 2>&1 &

这将有助于将程序日志存储在名为 "logger.txt"

的定义文件中