Brooks Johnson
Brooks Johnson

Reputation: 103

Clear the call stack in Python

I am fairly new to Python and stuck on what seems like a simple problem. After months of waiting, I figured I would give in and write my own bot to get my kids a PS5. but I am running into stack depth issues.

The program just looks to see if an item is available and if not if refreshed the page and tries again. But I am throwing an exception after 1000 calls. I have looked for a way to clear the stack in Python but have not found anything.

I have also tried to restart the program when the stack > 1000 with os. execv(). But this is throwing an Exec format error.

Below is a truncated version with all the login and setup stuff removed. Thank you in advance for any help!

def click_and_buy():
    try:
        print('trying to buy')
        buy_now = driver.find_element_by_xpath('//*[@id="buy-now-button"]')
        buy_now.click()
    except Exception as e:
        print(len(inspect.stack(0)))
        if len(inspect.stack(0)) < 5:
            click_and_buy()
            time.sleep(1)
        else:
            restart()


def restart():
    # os.system('ps5_bots.py')
    os.execv(__file__, sys.argv)


if __name__ == '__main__':
    click_and_buy()

Upvotes: 0

Views: 1044

Answers (1)

flakes
flakes

Reputation: 23684

Recursion is not a good fit for infinite repetitions. This is an x y problem.

Instead make the method iterative by using a while loop. Alternatively wrap the method with another that would invoke the loop:

def click_and_buy():
    print('trying to buy')
    buy_now = driver.find_element_by_xpath('//*[@id="buy-now-button"]')
    buy_now.click()


def click_and_buy_repeated():
    while True:
        click_and_buy()


if __name__ == '__main__':
    click_and_buy_repeated()

Upvotes: 3

Related Questions