Files
python-tests/subprocess_tests/subprocess_test_2.py
T

67 lines
1.9 KiB
Python
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
import locale
import os
import subprocess
if __name__ == "__main__":
print("*" * 100)
print(locale.getpreferredencoding())
print(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"
IMPORTANT:
不得不用的情况:如果必须要用 shell=True(比如必须调用系统内置命令),且涉及用户输入,
务必使用 shlex.quote()Linux/macOS)对用户输入进行转义过滤。
"""
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)