要通过Python命令管理Linux进程,您可以使用subprocess
模块
import subprocess
command = "echo 'Hello, World!'"
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
output, error = process.communicate()
if process.returncode == 0:
print("Process executed successfully:", output.decode('utf-8'))
else:
print("Error occurred while executing the process:", error.decode('utf-8'))
import os
import psutil
def get_process_list():
process_list = []
for process in psutil.process_iter(['pid', 'name']):
process_list.append({'pid': process.info['pid'], 'name': process.info['name']})
return process_list
print(get_process_list())
import os
import psutil
def kill_process(pid):
try:
process = psutil.Process(pid)
process.terminate()
print(f"Process {pid} terminated successfully.")
except psutil.NoSuchProcess:
print(f"Process {pid} not found.")
except psutil.AccessDenied:
print(f"Permission denied while trying to terminate process {pid}.")
pid = 12345
kill_process(pid)
请注意,这些示例可能需要根据您的需求进行调整。在使用subprocess
模块时,请确保正确处理权限和安全性问题。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。