从Raspberry Pi / Linux上的Python脚本运行和停止C++程序
Running and stopping a C++ program from a Python script on Raspberry Pi / Linux
我正在为我的项目使用 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
相关文章:
- 运行程序时出现问题
- 分段错误当我试图运行程序时出错
- C++ 每次运行程序时我都会"nan"输出的问题
- 通过 g++ 运行程序时没有这样的文件或目录
- 重新运行程序和字符串流?
- 无法在 VS Code 上使用代码运行程序运行C++文件
- 使用有限的 RAM 运行 c++ 程序
- 继续运行程序而无需任何干预,直到要求退出为止
- 如何在每次运行程序时写入文件的下一行?
- 控制台在运行C ++程序后立即关闭(无需调试)
- 运行程序时找不到共享对象库,但在编译过程中链接了它
- 远程运行程序
- 在 Heroku 上运行 C++ 程序
- 如何在Powershell中运行C++程序,就像CMD一样?
- 为什么与Java和Python相比,使用Cmake运行C++程序每次都需要这么长时间?
- C++随机数生成器通常在 Visual Studio 中运行程序时在 2 次后停止生成数字
- 崇高文本 3 - 在终端中编译并运行 C++ 程序(路径包含空格)
- 我收到阻止我运行程序的警告,但不确定如何解决
- C++ Visual Studio 无法完全运行程序
- 在SIGABRT c ++信号之后继续运行程序