我试图在 Ubuntu 启动时运行 Python 项目中的两个脚本,但一直出现问题。我有一个如下所示的 Python 项目:
- pycharm
- 韦恩
- 日期.txt
- 全局函数.py
- 網絡.txt
- 互联网日期.txt
- 互联网时间日志.txt
- 网络跟踪器
- 停电.txt
- 断电跟踪器.py
- 时间记录.txt
项目路径为/home/connor/Documents/Pycharm,IDE为Python 3.8.10的虚拟环境
我尝试运行的两个文件是 internettracker.py 和 poweroutagetracker.py。这两个代码如下:
网络跟踪器
import requests
import time
import globalfunctions as gf
url = "http://www.kite.com"
timeout = 5
def ping_internet():
try:
request = requests.get(url, timeout=timeout)
return True
except (requests.ConnectionError, requests.Timeout) as exception:
return False
gf.log_today(additional="internet")
while True:
internet_connected = ping_internet()
if internet_connected:
datestring, timenumber = gf.get_log(additional="internet")
curtime, today = gf.get_today()
if abs(curtime - timenumber) > 35:
gf.report_data("internet.txt", "Internet outage from [" + datestring + "] to [" + str(today) + "]")
print("Internet Outage Detected")
gf.log_today(additional="internet")
time.sleep(30)
else:
time.sleep(15)
断电跟踪器.py
import time
from datetime import datetime
import globalfunctions as gf
while True:
datestring, timenumber = gf.get_log()
curtime, today = gf.get_today()
if abs(curtime - timenumber) > 5:
gf.report_data("poweroutages.txt", "Power outage from [" + datestring + "] to [" + str(today) + "]")
print("Power Outage Detected")
time.sleep(5)
gf.log_today()
带有函数的支持文件 globalfunctions.py
import time
from datetime import datetime
def get_today():
return time.time(), datetime.today()
def log_today(additional=""):
curtime, today = get_today()
datefile = open(additional+"date.txt", "w")
datefile.write(str(today))
datefile.close()
timefile = open(additional+"timelog.txt", "w")
timefile.write(str(curtime))
timefile.close()
def get_log(additional=""):
datefile = open(additional+"date.txt", "r")
datestring = datefile.readline()
timefile = open(additional+"timelog.txt", "r")
timenumber = float(timefile.readline())
return datestring, timenumber
def report_data(filename, text):
curtime, today = get_today()
outfile = open(filename, "a+")
outfile.write(str(today) + " | " + text + "\n")
outfile.close()
我尝试按照以下说明进行操作此主题但它似乎不起作用。我创建了一个 .service,内容如下:
[Unit]
Description=Python Internet Watcher
[Service]
Type=simple
WorkingDirectory=/home/connor/Documents/Pycharm
ExecStart=./internettracker.py
[Install]
WantedBy=multi-user.target
该文件已被移至 /lib/systemd/system/ ,到目前为止,我没有看到启动时运行任何内容。
答案1
我找到了解决问题的方法。我发现您可以为项目激活虚拟环境,然后在虚拟环境中启动程序。
在项目中,可以通过 [project_path]/venv/bin/python 激活 venv
以下是解决方案的变更:
[Unit]
Description=Python Internet Watcher
After=network-online.target
[Service]
WorkingDirectory=/home/connor/Documents/Pycharm
ExecStart=/home/connor/Documents/Pycharm/venv/bin/python internettracker.py start
Restart=always
RestartSec=15s
KillMode=process
TimeoutSec=infinity
User=connor
Group=connor
[Install]
WantedBy=multi-user.target
命令行 python