🆕 Add new subprocess test file
This commit is contained in:
Executable
+53
@@ -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)
|
||||||
Reference in New Issue
Block a user