22

Python で次のようなスクリプトを作成することはできますか?

...
Pause
->
Wait for the user to execute some commands in the terminal (e.g.
  to print the value of a variable, to import a library, or whatever).
The script will keep waiting if the user does not input anything.
->
Continue execution of the remaining part of the script

基本的に、スクリプトは一時的に Python コマンド ライン インタープリターに制御を渡し、ユーザーが何らかの方法でその部分を終了した後に再開します。


私が思いついたのは(答えに触発されて)次のようなものです:

x = 1

i_cmd = 1
while True:
  s = raw_input('Input [{0:d}] '.format(i_cmd))
  i_cmd += 1
  n = len(s)
  if n > 0 and s.lower() == 'break'[0:n]:
    break
  exec(s)

print 'x = ', x
print 'I am out of the loop.'
4

5 に答える 5

36

Python 2.x を使用している場合:raw_input()

Python 3.x:input()

例:

# Do some stuff in script
variable = raw_input('input something!: ')
# Do stuff with variable
于 2012-11-21T20:16:11.640 に答える
2

私はあなたがこのようなものを探していると思います:

import re

# Get user's name
name = raw_input("Please enter name: ")

# While name has incorrect characters
while re.search('[^a-zA-Z\n]',name):

    # Print out an error
    print("illegal name - Please use only letters")

    # Ask for the name again (if it's incorrect, while loop starts again)
    name = raw_input("Please enter name: ")
于 2014-06-16T19:39:49.447 に答える