在Python中,可以使用subprocess
模块中的run
函数来执行系统命令或脚本。以下是一些执行脚本的技巧:
import subprocess
result = 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)
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())
这些技巧可以帮助你更方便地执行系统命令或脚本,并处理相应的输出和错误信息。请注意安全性,尽量避免直接在脚本中执行用户输入的命令。