我正在尝试在运行 CentOS 7 的 VPS 上放置一个 python 脚本,该脚本从 Web 服务在线抓取一些股票数据。我想要做的是将这个脚本设置为在特定时间启动/停止的操作系统服务。
我该怎么做?
编辑:这是结果systemctl status python-script
Loaded: loaded (/etc/systemd/system/python-script.service; enabled; vendor preset: disabled)
Active: failed (Result: exit-code) since Sat 2020-05-16 01:11:50 +0430; 15h ago
Main PID: 854 (code=exited, status=1/FAILURE)
May 16 01:11:43 boiga.server1.more.com systemd[1]: Started Python Script Serv...
May 16 01:11:50 boiga.server1.more.com python3[854]: Traceback (most recent c...
May 16 01:11:50 boiga.server1.more.com python3[854]: File "/root/script.py", ...
May 16 01:11:50 boiga.server1.more.com python3[854]: await (websocketConnect())
May 16 01:11:50 boiga.server1.more.com python3[854]: NameError: name 'await' ...
May 16 01:11:50 boiga.server1.more.com systemd[1]: python-script.service: mai...
May 16 01:11:50 boiga.server1.more.com systemd[1]: Unit python-script.service...
May 16 01:11:50 boiga.server1.more.com systemd[1]: python-script.service failed.
Hint: Some lines were ellipsized, use -l to show in full.
答案1
您可以通过创建服务文件来创建运行此 python 脚本的服务/etc/systemd/system/python-script.service
,如下例所示:
[Unit]
Description=Python Script Service
After=network.target
[Service]
Type=simple
User=root
ExecStart=/usr/bin/python3 /root/script.py
Restart=on-abort
[Install]
WantedBy=multi-user.target
然后运行systemctl daemon-reload
以重新加载 systemd 并systemctl enable python-script
启用该服务。
运行该服务应该会给出如下结果:
systemctl status python-script
● python-script.service - Python Script Service
Loaded: loaded (/etc/systemd/system/python-script.service; enabled; vendor preset: disabled)
Active: inactive (dead) since Wed 2020-05-13 23:10:30 CEST; 2s ago
Process: 27405 ExecStart=/usr/bin/python3 /root/script.py (code=exited, status=0/SUCCESS)
Main PID: 27405 (code=exited, status=0/SUCCESS)
May 13 23:10:30 server1 systemd[1]: Started Python Script Service.
May 13 23:10:30 server1 python3[27405]: Hello World!
关于计划服务的启动/停止,您可以使用 crontab 来实现