在Python中,可以使用subprocess模块中的run函数来执行系统命令或脚本。以下是一些执行脚本的技巧:
import subprocessresult = subprocess.run(["ls", "-l"], stdout=subprocess.PIPE)print(result.stdout.decode())检查命令的返回值:result = subprocess.run(["ls", "non_existent_file"], stdout=subprocess.PIPE)if result.returncode != 0: print("Command failed with error code:", result.returncode)在shell中执行命令(可以使用通配符等特殊字符):result = subprocess.run("ls *.txt", shell=True, stdout=subprocess.PIPE)print(result.stdout.decode())传递参数给脚本:name = "Alice"result = subprocess.run(["./hello.sh", name], stdout=subprocess.PIPE)print(result.stdout.decode())获取命令的输出和错误信息:result = subprocess.run(["ls", "non_existent_file"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)if result.returncode != 0: print("Error:", result.stderr.decode())设置工作目录:result = subprocess.run(["ls"], cwd="/path/to/directory", stdout=subprocess.PIPE)print(result.stdout.decode())这些技巧可以帮助你更方便地执行系统命令或脚本,并处理相应的输出和错误信息。请注意安全性,尽量避免直接在脚本中执行用户输入的命令。