Restart application in Python

1

How do I restart my program with Python?

cpf = input('Digite os nove primeiros dígitos do CPF: ')

if len(cpf) != 9:
    # Aqui deve reniciar a aplicação.
    
asked by anonymous 03.03.2017 / 04:04

3 answers

3

If you want to request the data again it would look like this:

while True: #inicia o laço
    cpf = input('Digite os nove primeiros dígitos do CPF: ')
    if len(cpf) == 9: #se está ok não precisa mais continuar o laço
        break
    #possivelmente mais código aqui

See running on ideone . And No Coding Ground . Also put it on GitHub for future reference .

Essentially in console applications this is how it is done. Of course you have to abstract so you do not get repetitive. There are other techniques for joining together.

    
03.03.2017 / 04:16
2

To restart your application you can create the following method:

import sys
import os
def restart_program():
    python = sys.executable
    os.execl(python, python, * sys.argv)

Then when you want to restart the application you call:

restart_program()

More depending on the problem you can do a simple loop repetition for example:

while True:
    cpf = input('Digite os nove primeiros dígitos do CPF: ')
    if len(cpf) == 9:
        break
    else:
        continue

I think in your case working with the loop would be the best option

    
03.03.2017 / 04:19
-1

Actually, the comment above is correct, but if it is something to just call the option to enter the CPF again, you can use the repetition (as in the comment above):

cpf = input('Digite os nove primeiros dígitos do CPF: ')
if len(cpf) != 9:
     break
     #Para a operação
else:
     continue
    
27.03.2018 / 17:15