用Python的subprocess模块来执行Linux命令
这个函数会执行类似于 ps aux | grep python | awk '{print $2}' | xargs kill -9
的Linux命令。你可以将参数 process_name
替换为你想要杀死的进程名。
import subprocess def kill_process(process_name): p1 = subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE) p2 = subprocess.Popen(["grep", process_name], stdin=p1.stdout, stdout=subprocess.PIPE) p3 = subprocess.Popen(["awk", "{print $2}"], stdin=p2.stdout, stdout=subprocess.PIPE) p4 = subprocess.Popen(["xargs", "kill", "-9"], stdin=p3.stdout) p1.stdout.close() p2.stdout.close() p3.stdout.close() output, error = p4.communicate() if error: print(f"Error: {error}") else: print(f"Process {process_name} killed successfully.") # Example usage kill_process("python")
import subprocess # 构建命令 command = 'curl http://localhost:6800/schedule.json -d project=abc' # 运行命令 p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # 获取输出 out, err = p.communicate() # 输出结果 print(out.decode('utf-8'))