私は現在、個人的なプロジェクトのためにプログラムの一部を作成していますが、その 1 つの側面について助けが必要です。
プログラムの仕組みは次のとおりです。
- ユーザーが実行する時間を入力します
- ユーザーがテキストを入力 - ファイルが変更されます
- タイマーが開始されました
- オプションユーザーは「パスワード」を入力してタイマーを中断できます
- アクションが反転する
これを行う最善の方法を見つけようとしているので、タイマーを除くすべての手順をコーディングしました。理想的には、タイマーにカウントダウンを表示させたいのですが、ユーザーが特定の「パスワード」を入力すると、タイマーが中断され、ステップ番号 5 にスキップします。
これを行う最善の方法は、スレッドを使用することでしょうか? 私は過去にスレッドをあまり扱っていませんでした。ユーザーがそのパスワードを入力したい場合に備えて、ユーザーに制御を戻しながら、タイマーを表示するために何らかの方法が必要です。
ご協力いただきありがとうございます。
コードは次のとおりです。
import time
import urllib
import sys
def restore():
backup = open(r'...backupfile.txt','r')
text = open(r'...file.txt', 'w+')
text.seek(0)
for line in backup:
text.write(line)
backup.close()
text.close()
text = open(r'...file.txt', 'a+')
backup = open(r'...backupfile.txt','w+')
text.seek(0)
for line in text:
backup.write(line)
backup.close()
while True:
url = raw_input('Please enter a URL: ')
try:
if url[:7] != 'http://':
urllib.urlopen('http://' + url)
else:
urllib.urlopen(url)
except IOError:
print "Not a real URL"
continue
text.write(url)
while True:
choice = raw_input('Would you like to enter another url? (y/n): ')
try:
if choice == 'y' or choice == 'n':
break
except:
continue
if choice == 'y':
text.seek(2)
continue
elif choice == 'n':
while True:
choice = raw_input('Would you to restore your file to the original backup (y/n): ')
try:
if choice == 'y' or choice == 'n':
break
except:
continue
if choice == 'y':
text.close()
restore()
sys.exit('Your file has been restored')
else:
text.close()
sys.exit('Your file has been modified')
ご覧のとおり、タイミング部分はまだ追加していません。URL をテキスト ファイルに追加して閉じるだけです。ユーザーが元のファイルを必要とする場合は、reverse() が呼び出されます。