Python スクリプトを使用して、バッチ ファイルを含むプロセスを自動化しています。これらは他のアプリケーションで使用されるバッチ ファイルであり、編集することはできません。
バッチ ファイルの最後に、次のプロンプトが表示されます。
"何かキーを押すと続行します ..."
このプロンプトが表示されたときに Python を使用して認識するにはどうすればよいですか? また、それに応答するにはどうすればよいですか? 次のバッチ ファイルを実行できるように、ファイルを閉じることができるようにしたいと考えています。
現在、私は次の解決策を見つけましたが、それはひどいもので、内部が汚れていると感じます:
#Run the batch file with parameter DIABFile
subprocess.Popen([path + '\\' + batchFile, path + '\\' + DIABFile])
#Sit here like an idiot until I'm confident the batch file is finished
time.sleep(4)
#Press any key
virtual_keystrokes.press('enter')
何か案は?
試み #1
p = subprocess.Popen([path + '\\' + batchFile, path + '\\' + DIABFile],
bufsize=1, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
while p.poll() is None:
line = p.stdout.readline()
print(line)
if line.startswith('Press any key to continue'):
p.communicate('\r\n')
次の出力とエラーが発生しました。
b'\r\n'
Traceback (most recent call last):
File "C:\workspace\Perform_QAC_Check\Perform_QAC_Check.py", line 341, in <module>
main()
File "C:\workspace\Perform_QAC_Check\Perform_QAC_Check.py", line 321, in main
run_setup_builderenv(sandboxPath, DIABFile)
File "C:\workspace\Perform_QAC_Check\Perform_QAC_Check.py", line 126, in run_setup_builderenv
if line.startswith('Press any key to continue'):
TypeError: startswith first arg must be bytes or a tuple of bytes, not str
The process tried to write to a nonexistent pipe.
私にとって最も奇妙に思えたのは、startswith の最初の引数が、str ではなくバイトまたはバイトのタプルでなければならないことです。私はドキュメントを調べましたが、それは間違いなく文字列である必要がありますか? startswith のチュートリアル
だから私はオンラインで見て、これを少し見つけました。
エラー メッセージは、まったく逆であるため、Python のバグのようです。それでも、ここでは問題ありません。indian.py の 75 行目の後に追加します
try:
line = line.decode()
except AttributeError:
pass
そしてそうしました。
試み #2
p = subprocess.Popen([path + '\\' + batchFile, path + '\\' + DIABFile],
bufsize=1, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
while p.poll() is None:
line = p.stdout.readline()
print(line)
try:
line = line.decode()
if line.startswith('Press any key to continue'):
p.communicate('\r\n')
except AttributeError:
pass
次の出力が得られました。
b'\r\n'
b'Build Environment is created.\r\n'
b'\r\n'
b'Please Refer to the directory: C:/directory\r\n'
b'\r\n'
そして、そこでハングします...これは、「続行するには何かキーを押してください」が表示される前の最後の出力ですが、決して表示されません。
ノート
それ以来、2 番目のスクリプトを使用して、「参照してください」を検索するように依頼しました。残念ながら、スクリプトは次の行で再びハングします。
p.communicate('\r\n')
プログラムを終了すると、再びエラーが出力されます。
The process tried to write to a nonexistent pipe.
これは、このバグに関連していると思います。
私がやろうとしていることは、それが普通ではないことだとは想像できません。これは予想より少し複雑に見えるので、私は XP と Python バージョン 3.3 を使用していると言いたいです。