如何将函数调用与此函数分开

时间:2018-01-25 15:12:13

标签: python function import

我有一个现有的脚本,其中包含我想从另一个脚本调用的函数。我想修改它,使main函数不会自动调用primitives函数。

完整的脚本如下:

import time
import datetime
from luma.core.render import canvas


def primitives1(device, draw):
    # First define some constants to allow easy resizing of shapes.
    padding = 2
    shape_width = 20 
    top = padding
    bottom = device.height - padding - 1
    # Move left to right keeping track of the current x position for drawing shapes.
    x = padding
    # Write two lines of text.
    size = draw.textsize('World!')
    x = device.width - padding - size[0]
    draw.rectangle((x, top + 4, x + size[0], top + size[1]), fill="black")
    draw.rectangle((x, top + 16, x + size[0], top + 16 + size[1]), fill="black")
    draw.text((device.width - padding - size[0], top + 4), 'Hello', fill="cyan") 
    draw.text((device.width - padding - size[0], top + 16), 'World!', fill="purple") 
    time.sleep(5)

    def primitives2(device, draw):
    # First define some constants to allow easy resizing of shapes.
    padding = 2
    shape_width = 20 
    top = padding
    bottom = device.height - padding - 1
    # Move left to right keeping track of the current x position for drawing shapes.
    x = padding

    # Write two lines of text.
    size = draw.textsize('World!')
    x = device.width - padding - size[0]
    draw.rectangle((x, top + 4, x + size[0], top + size[1]), fill="black")
    draw.rectangle((x, top + 16, x + size[0], top + 16 + size[1]), fill="black")
    draw.text((device.width - padding - size[0], top + 4), 'Bye', fill="cyan") 
    draw.text((device.width - padding - size[0], top + 16), 'Bye!', fill="purple") 
    time.sleep(5)    

def main():
    from luma.core.interface.serial import spi
    from luma.core.render import canvas
    from luma.oled.device import ssd1351
    serial = spi(device=0, port=0, gpio_DC=20)
    device = ssd1351(serial)
    device.width=128
    device.height=128
    print("Testing basic canvas graphics...")
    for _ in range(2):
        with canvas(device) as draw:
            primitives1(device, draw)
    time.sleep(3)
    print("Testing clear display...")
    time.sleep(1)
    device.clear()



if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        pass

我是否可以从primitives1(device, draw)移除def main但仍保留with canvas(device) as draw:?如果我在不调用with canvas(device) as draw:的情况下离开primitives1,如果我尝试启动脚本,则终端会输出错误。

我之所以这样做,是因为我可以先使用其他脚本拨打main(),然后选择拨打primitives1primitives2

1 个答案:

答案 0 :(得分:1)

我会修改main函数以接受primitivesX函数定义。你想这样使用......

def main(prim_func):
    ...
    for _ in range(2):
        with canvas(device) as draw:
            prim_func(device, draw)

然后你会调用像......这样的主要内容。

main(primitives1) 
or...
main(primatives2)

请注意,传入函数的声明名称,而不是它的实例。当然,请确保在脚本中的某个位置定义名称或导入名称。