簡體   English   中英

從python腳本中重新運行腳本的命令

[英]Command to re-run script from within the script in python

仍在從事我的子手游戲! 我想定義一個函數,該函數重新運行整個python腳本-即,如果將“是”稱為其參數,則會重置要猜測的單詞,空格數量,猜測的字母和子手圖。 我嘗試使用內置的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')

我懂了

a n d  

- b c - - f g h i j k - m - o p q - s t - v w x y z
  _________
 ||       |
 ||       0
 ||     /( )\
 ||
 ||
 ||
 ||_________

這表明,盡管guess()函數在再次播放后似乎可以很好地重置,但其余代碼與待猜測單詞的長度保持不變。 據我所知,subprocess()函數具有類似的效果/也沒有起作用。 是否有一種簡單的方法可以重新運行整個腳本,以便將其全部重置?

不知道您是否需要整個腳本來為我提供答案(我也不知道是否不包括它是愚蠢的),因此,如果您需要所有這些內容,我會編輯這篇文章,但我想我將不包括所有內容,而僅包括play_again函數,以使其盡可能短。 希望一切都清楚!

play_again函數:

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循環解決此問題,一旦用戶想要停止,該循環就會中斷。 使用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循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM