我正在尝试创建一个Python脚本生成工具,该工具根据某些操作创建Python文件。例如:
action = "usb" # dynamic input to script
dev_type = "3.0" # dynamic input to script
from configuration import config
if action == "usb":
script = """
#code to do a certain usb functionality
dev_type = """ + dev_type + """
if dev_type == "2.0"
command = config.read("USB command 2.0 ")
proc = subprocess.Popen(command,stdout=subprocess.PIPE,
stderr=subprocess.PIPE, shell=False)
elif dev_type == "3.0":
command = config.read("USB command 3.0 ")
proc = subprocess.Popen(command,stdout=subprocess.PIPE,
stderr=subprocess.PIPE, shell=False)
"""
elif action == "lan":
script = """
#code to run a certain lan functionality for eg:
command = config.read("lan command")
proc = subprocess.Popen(command,stdout=subprocess.PIPE,
stderr=subprocess.PIPE, shell=False)
"""
with open("outputfile.py", w) as fl:
fl.writelines(script)
实际的脚本生成器非常复杂。 我生成" outputfile.py"我的本地计算机中的脚本将操作输入到脚本,然后将生成的脚本部署到远程计算机以记录结果。这是更大框架的一部分,我需要保留这种执行格式。
每个"脚本" block使用config.read函数来读取从配置文件运行所需的某些变量。 "命令"在上面的例子中。
我的实际框架工作在配置文件中有大约800个配置 - 我在远程机器上部署它以及要运行的脚本。因此,该文件中有许多额外配置可能不是特定脚本运行所必需的,并且不是非常用户友好。
我正在寻找的是基于"脚本"写入输出文件的块 - 创建一个自定义配置文件,该文件仅包含该脚本运行所需的配置。
例如,如果操作是" lan",则下面的脚本块将写入输出文件
script = """
#code to run a certain lan functionality for eg:
command = config.read("lan command")
proc = subprocess.Popen(command,stdout=subprocess.PIPE,
stderr=subprocess.PIPE, shell=False)
"""
我想要的只是" lan命令"在我的自定义配置文件中。
我的问题是: 我如何评估"脚本"阻止(在三重引号内)知道在该代码中使用了哪个配置,然后在写入输出文件时将该配置写入我的自定义配置文件?
"脚本中可能有多个if条件"块也。我不想配置" USB命令2.0"和" USB命令3.0"在自定义配置文件中,如果action =" usb"和dev_type =" 3.0"
当然我无法在"脚本中执行代码"阻止 - 然后拦截config.read()函数,将调用的配置写入我的自定义配置文件。有没有更好的方法呢?