从Raspberry Pi / Linux上的Python脚本运行和停止C++程序

Running and stopping a C++ program from a Python script on Raspberry Pi / Linux

本文关键字:运行 程序 C++ 脚本 Python Pi Raspberry Linux 上的      更新时间:2023-10-16

我正在为我的项目使用 Google Cloud Firestore 数据库。我正在尝试使用 Python 从数据库中检索数据,这是一个简单的变量(1 或 0(。

因此,如果我从数据库中得到一个"1",我想从当前的 Python 程序执行一个C++程序。如果我得到"0",我想终止正在运行的程序。

我对此有一些疑问,

从python运行C++文件非常简单,但是如何 我是否终止它以及如何在尝试终止它之前检查它是否未运行

以下是我的蟒蛇代码

import firebase_admin
import time
from firebase_admin import credentials
from firebase_admin import firestore
n=1
b=None
cred = credentials.Certificate('/Users/vijaypenmetsa/Desktop/key.json')
firebase_admin.initialize_app(cred)
db = firestore.client()
def on_snapshot(doc_snapshot, changes, read_time):
for doc in doc_snapshot:
a = doc.to_dict()
b = a["status"]
check(b)
#b is the variable retrieved from the database
def check(c):
if c == 1:
print("Start Driving")
elif c == 0:
print("Halt")
doc_ref = db.collection(u'status').document(u'carstatus')
while n>0:
doc_watch = doc_ref.on_snapshot(on_snapshot)
time.sleep(10)

您可以使用 psutil 查看进程是否正在运行。这里有一个链接肯定会帮助你:https://thispointer.com/python-check-if-a-process-is-running-by-name-and-find-its-process-id-pid/

最终代码如下:

import psutil
def checkIfProcessRunning(processName):
'''
Check if there is any running process that contains the given name processName.
'''
#Iterate over the all the running process
for proc in psutil.process_iter():
try:
# Check if process name contains the given name string.
if processName.lower() in proc.name().lower():
return True
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
return False;

if checkIfProcessRunning('chrome'):
print('Yes a chrome process was running')
else:
print('No chrome process was running')

在这种情况下,我使用的是这家伙的示例,因此请检查 chrome 是否正在运行,但您可以检查您想要的任何内容

您可能希望通过在终端上运行以下代码来让 pip 为您安装 psutil:

pip3 install psutil

pip install psutil