Цикл while запрашивает запись input () два раза в скрипте Python - PullRequest
0 голосов
/ 23 мая 2019

Я использую Python 3.7.1 (по умолчанию, 14 декабря 2018, 19:28:38).

Прежде всего, мой сценарий работает правильно, когда я ввожу правильную запись в input() во второй раз, но я предпочитаю, чтобы она запрашивалась только один раз. В своем коде я написал print() строки, чтобы увидеть, что происходит в режиме реального времени, и именно здесь я не понимаю, что происходит при выполнении.

Давайте посмотрим сценарий:

import subprocess
from scrapy import cmdline
import sys

champ_choix = ""
while champ_choix != "1" and champ_choix != "2":
    champ_choix=input("Pour cat_course tapez 1\nPour hippodrome tapez 2\n")
    print("L'input est : {}".format(champ_choix)) #the input is:
    print("le type de l'input est: {}".format(type(champ_choix))) #the type of input is:
    if champ_choix == "1": #Traite le champ hippodrome
        print("on a le champ_choix 1") #we have got choice 1
        #do instructions
        sys.exit() #to stop the script and stop asking once again an entry after it is done
    if champ_choix == "2":
        print("le champ_choix est 2") #we have got choice 2
        cmdline.execute(['scrapy','crawl','test_shell','-a','nom_prix=True'])
        sys.exit()

Теперь, что у меня в терминале:

Pour cat_course tapez 1
Pour hippodrome tapez 2
2 # here a good entry
L'input est : 2 # it says it is a good entry
le type de l'input est: <class 'str'> # it even says that's the good type
le champ_choix est 2 # it even says it is in the second `if` condition
Pour cat_course tapez 1 # but it asks once again, without executing instructions
Pour hippodrome tapez 2
2 # a good entry once more
L'input est : 2
le type de l'input est: <class 'str'>
le champ_choix est 2 # in the second `if` condition and now gonna finally execute instructions
#Running the spider as expected, that is alright
#Stop and exit, it is alright too

Что не так?

1 Ответ

1 голос
/ 23 мая 2019

Хорошо сформулированный вопрос (реквизиты для предоставления stdout), но убедитесь, что вы делаете правильный интервал (то есть должен быть пробел до и после операторов, таких как a == b).

1) Не используйте sys.exit(), просто используйте break.

2) Вам необходимо заполнить цикл.Другими словами, сделайте один ввод до того, как вы
войдете в цикл, затем продолжайте ввод в конце КОНЦА:

import subprocess
from scrapy import cmdline
import sys

while True: 
    champ_choix = input("Pour cat_course tapez 1\nPour hippodrome tapez 2\n")

    # This first if isn't needed because the if at the bottom catches this case
    # if champ_choix == "1": #Traite le champ hippodrome
    #     break
    if champ_choix == "2":
        cmdline.execute(['scrapy','crawl','test_shell','-a','nom_prix=True'])
    if champ_choix in ["1", "2"]:
        break
...