From 9e82fbc64f18f14ce1f34ebf9ad3ae349a521d50 Mon Sep 17 00:00:00 2001 From: Hatter Jiang Date: Sat, 23 May 2026 23:58:53 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=86=95=20Add=20new=20subprocess=20test=20?= =?UTF-8?q?file?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- subprocess_test_2.py | 53 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100755 subprocess_test_2.py diff --git a/subprocess_test_2.py b/subprocess_test_2.py new file mode 100755 index 0000000..4dd0447 --- /dev/null +++ b/subprocess_test_2.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 + +import locale +import os +import subprocess + +if __name__ == "__main__": + print("*" * 100) + print(locale.getpreferredencoding()) + + print("*" * 100) + result = subprocess.run( + ['env'], + capture_output=True, + ) + result.check_returncode() + print('return code:', result.returncode) + print(result.stdout) + print("*" * 100) + result = subprocess.run( + ['env'], + capture_output=True, + text=True, + encoding='utf-8', + ) + result.check_returncode() + print('return code:', result.returncode) + print(f"{result.stdout[:100]}******") + + print("*" * 100) + subprocess.run( + ['env'], + env={"NAME": "hatter"}, + ) + + print("*" * 100) + my_env = os.environ.copy() + my_env["NAME"] = "hatter" + subprocess.run( + ['sleep', '5'], + env=my_env, + check=True, # 非 0 返回时抛出异常 + ) + + print("*" * 100) + subprocess.Popen( + ['sleep', '50'], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + preexec_fn=os.setpgrp # 让子进程独立,即使当前脚本挂了它也继续运行 + ) + + print("*" * 100)