下面是一个Python读取JSON文件并拼接Linux命令执行的简单案例:
json文件
假设有一个JSON文件commands.json,内容如下
[
{
"command": "ls",
"args": ["-l", "/home/xmaster/1.sql"]
},
{
"command": "cat",
"args": ["/home/xmaster/1.sql"]
}
]
python脚本
使用Python读取该文件,并将其中的命令和参数拼接成Linux命令执行:
#!/usr/bin/python3
#-*-coding:utf-8-*-
import json
import subprocess
# 读取JSON文件
with open('commands.json', 'r') as f:
commands = json.load(f)
# 拼接命令
for cmd in commands:
command = [cmd['command']] + cmd['args']
print(' '.join(command))
# 执行命令
subprocess.run(command)
结果
[xmaster@mogdb-kernel-0005 demo4_py_read_json]$ python3 read_and_exec.py
ls -l /home/xmaster/1.sql
-rw-r--r-- 1 xmaster dbaa 7 May 31 01:01 /home/xmaster/1.sql
cat /home/xmaster/1.sql
heiheia