我正在使用pyinfra提供一些文件。我想知道放置自定义模块的最佳位置。
示例
给定一个自定义事实,如果系统不是无头的,则返回True:
class HasGui(FactBase):
default = list
command = 'ls /usr/share/xsessions/*.desktop || true'
def process(self, output):
return output问题
我该把这个放哪儿?我想我可以将这个代码片段直接编码到一个“操作”文件中,但是如果我想在几个模块中重用这段代码呢?如何将其抽象为单独的模块或从API中访问它?
虽然数据可以跨模块共享。,推荐的布局似乎不容易允许自定义模块挂钩到API。
逼近
sys.path添加路径,但我更喜欢一个更干净的选项。发布于 2020-10-02 05:31:53
此错误建议可以从位于在“部署”文件旁边的顶级config.py文件中检测到自定义事实。
码
在配置中编码的自定义事实(可选)。还请参阅示例布局
# config.py
from pyinfra.api import FactBase
class HasGui(FactBase):
default = list
command = 'ls /usr/share/xsessions/*.desktop || true'
def process(self, output):
return output注意:尾随的|| true防止pyinfra在失败时出错。尽管持续不断,但故障似乎是在内部处理的。
当自定义事实子类FactBase时,它将被添加到事实指数中。您可以通过蛇形属性访问它们。
# tasks/operation.py
from pyinfra import host
if host.fact.has_gui:
# Insert operation
...Demo
在命令行中运行。
> pyinfra @local tasks/operation.py
[@local] Successful: 1 Errors: 0 Commands: 1/1
> pyinfra @<server> tasks/operation.py
[@local] Successful: 0 Errors: 0 Commands: 1/1发布于 2022-09-05 06:54:25
在实际版本中,对我来说,它的工作方式如下:
碱基: /home/pyinfra
我有一个带有自定义事实和操作(和文件)的(定制/事实):
例如,/home/pyinfra/custom/facts/FileFacts.py
from pyinfra.api import FactBase
class FileExists(FactBase):
'''
Returns if file exists (true/false)
'''
__filepath = ""
def command(self, path):
""" Checks if app exists via linux ls command """
self.__filepath = path
return 'ls {0}'.format(path)
def process(self, output):
# ls should return the path itself if it exists
if str(output[0]) == self.__filepath:
return True
return False 然后在我的任务中,我可以导入并调用它
from custom.facts.FileFacts import FileExists
if host.get_fact(FileExists, "/etc/app/config"):
logger.info("File already exits!")
else:
logger.info("File does not exist!")(如果代码本身不完美,请不要挂起我的电话,尽管对有用的输入表示赞赏,但它对我的情况来说已经足够了)
https://stackoverflow.com/questions/64165507
复制相似问题