如何减少这段代码的长度?

时间:2019-11-29 09:15:43

标签: python pyautogui

我已经设法为我的Samsung软件包更新开发了一个自动化脚本,但是它的长度困扰着我。我运行它时效果很好,但我认为缩短长度会更有效。有什么方法可以缩短这个时间?

def package1():
    try:
        #move to model name and click
        gui.moveTo(x=1016, y=701, duration=1.0)
        gui.click()
        print 'Navigating to Package'
        time.sleep(15)

        #move to update name and click
        gui.moveTo(x=661, y=526, duration=1.0)
        gui.click()
        print 'Navigating to Update version'
        time.sleep(15)

        #save setup file popup, move to save button
        gui.moveTo(x=1155, y=800, duration=1.0)
        gui.click()
        print 'Save setup popup'
        time.sleep(5)

        #navigate documents folder
        print 'Navigating to Documents'
        gui.moveTo(x=675, y=370, duration=1.5)
        gui.click()
        time.sleep(2)

        #navigate to date today folder
        print 'Navigating to Update folder'
        gui.moveTo(x=885, y=356, duration=1.5)
        gui.click(clicks=2)
        gui.moveTo(x=885, y=356, duration=1.5)
        gui.click(clicks=2)
        time.sleep(2)

        #navigate to which windows v folder and save to start downloading
        gui.moveTo(x=881, y=378, duration=1.0)
        gui.click()
        gui.moveTo(x=1315, y=738, duration=1.0)
        gui.click()
        print 'Downloading package...'
        time.sleep(240)
        print 'Package finished downloading, check for errors'
        gui.moveTo(x=1178, y=637, duration=1.0)
        gui.click()
        gui.moveTo(x=1260, y=798, duration=1.0)
        gui.click()
        gui.moveTo(x=618, y=393, duration=1.0)
        gui.click()

except KeyboardInterrupt:
        print 'Program stopped..'

2 个答案:

答案 0 :(得分:4)

如果您看到一部分代码重复出现,那么在大多数情况下,您可以创建一个函数。

也许像……

def move_and_click(x,y,duration,sleep, name=""):
    gui.moveTo(x=x, y=y, duration=duration)
    gui.click()
    print 'Navigating to {}'.format(name)
    time.sleep(sleep)

def package1():
    try:
        move_and_click(10,12,1.0,15, "test")
        ...

如果您想创建一个主函数,则可以将x和y读作列表,然后移动并单击该列表中的每个项目...(以确保它也适用于“导航到今天的文件夹”)< / p>

答案 1 :(得分:2)

虽然Brizar的回答相当不错,但您可能希望此功能接受一系列的移动/单击指令。此类指令应作为元组(或命名元组)的可迭代形式传递。

def move_and_click_2(instructions, sleep, name=None):
    for x,y,duration in instructions:
        gui.moveTo(x=x, y=y, duration=duration)
        gui.click()
    if name is not None:
        print 'Navigating to {}'.format(name)
    time.sleep(sleep)

def package1():
    try:
        move_and_click2([(10,12,1.0)],15, "test")
        move_and_click2([(30,20,1.0),(20,22,2.0)],15, "test2")