Files
python-tests/subprocess_test_2.py
T

79 lines
2.2 KiB
Python
Executable File

#!/usr/bin/env python3
import locale
import os
import subprocess
if __name__ == "__main__":
print("*" * 100)
print(locale.getpreferredencoding())
# locale.getencoding() # from Python3.11
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)
"""
当设置 shell=True 时,你可以使用只有系统 Shell 才支持的“高级语法”:
- 管道和重定向:比如 "cat file.txt | grep 'error' > result.txt"
- 环境变量解析:比如 "echo $USER" (Linux) 或 "echo %USERNAME%" (Windows)
- Shell 内置命令:有些命令(如 Windows 的 dir, copy 或 Linux 的 export)并不是独立的可执行文件,
而是 Shell 的内置命令。如果不设 shell=True,Python 会报错找不到文件。
- 通配符展开:比如 "rm *.txt"
"""
subprocess.run(
'echo ">>>>>>>>>>>>" && env && echo "<<<Hello World!>>>"',
env={"NAME": "hatter"},
shell=True,
)
print("*" * 100)
my_env = os.environ.copy()
my_env["NAME"] = "hatter"
subprocess.run(
['sleep', '5'],
env=my_env,
check=True, # 非 0 返回时抛出异常,相当于 result.check_returncode()
)
print("*" * 100)
subprocess.Popen(
['sleep', '50'],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
preexec_fn=os.setpgrp # 让子进程独立,即使当前脚本挂了它也继续运行 for Linux/Unix/MacOS
)
# for Windows
# flags = 0x00000008 | 0x00000200
# process = subprocess.Popen(
# ["cmd", "/c", "your_script.bat"],
# stdout=subprocess.DEVNULL,
# stderr=subprocess.DEVNULL,
# creationflags=flags
# )
print("*" * 100)