Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jsp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
命令从python中的脚本中重新运行脚本_Python - Fatal编程技术网

命令从python中的脚本中重新运行脚本

命令从python中的脚本中重新运行脚本,python,Python,还在做我的刽子手游戏!我想定义一个函数,它可以重新运行整个python脚本——即重置要猜测的单词、空格数、猜测的字母和hangman图——如果将“yes”作为其参数调用。我尝试过使用内置的execfile函数,但如果新词的长度与前一个不同,则只会添加空格或删除字母: In [17]: attempt(word, 'r') u n d e r a b c - - f g h i j k - m - o p q - s t - v w x y z _________ || |

还在做我的刽子手游戏!我想定义一个函数,它可以重新运行整个python脚本——即重置要猜测的单词、空格数、猜测的字母和hangman图——如果将“yes”作为其参数调用。我尝试过使用内置的execfile函数,但如果新词的长度与前一个不同,则只会添加空格或删除字母:

In [17]: attempt(word, 'r')
u n d e r  

a b c - - f g h i j k - m - o p q - s t - v w x y z
  _________
 ||       |
 ||
 ||       
 ||
 ||
 ||
 ||_________

Congratulations! You guessed the correct word!

Would you like to play again?
是上一场比赛的结果,当我写

In [18]: play_again('yes')

In [19]: word = ['a','c','e']

In [20]: guess(word)
>>>       _________
         ||       |
         ||
         ||       
         ||
         ||
         ||
         ||_________

In [21]: attempt(word, 'a')
我明白了

这表明,虽然再次播放后guess函数似乎重置得很好,但除了要猜测的单词长度外,其余代码保持不变。根据我的记忆,subprocess函数也有类似的效果/也不起作用。有没有一种简单的方法可以重新运行整个脚本,使其全部重置

我不知道你是否需要整个脚本来给我一个答案,我也不知道我不包括它是否是愚蠢的,所以如果你需要它,我会编辑这篇文章,但我想我会尽可能地简短,不包括所有内容,只是暂时再包括play_功能。希望一切都清楚

再次播放功能:

def play_again(decision=''):
if decision == 'yes':
    execfile("C:\Users\Joel\Documents\Year 1\Labs\Computing\Learning\hangmanglobal.py")
if decision == 'no':
    print "Thank you for playing Hangman!"

您应该使用while循环来解决这个问题,一旦用户想要停止,while循环就会中断。使用execfile进行此操作相当尴尬,如果您移动脚本,将导致中断

伪代码:

while True:
    # initialize variables
    # redraw your graphics
    # play the game
    # ask user if he wants to play another game
    if not play_again:
        break

print('Thanks for playing, bye')
最好您应该为上述步骤调用函数,以避免出现巨大的while循环。

您应该使用while循环而不是调用execfile来解决这个问题。让你的主程序包括在while-True循环中初始化变量,当用户决定结束游戏时,该循环会中断。
while True:
    # initialize variables
    # redraw your graphics
    # play the game
    # ask user if he wants to play another game
    if not play_again:
        break

print('Thanks for playing, bye')