我正在使用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
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.
对我来说似乎最奇怪的部分是firstwith first arg必须是字节或字节元组,而不是str.我查了一下文档,它肯定应该是一个字符串? tutorial of startswith
所以我在网上找了this一点点.
The error message seems to be a bug in Python, as it is exactly the other way around. But still, no problems here, add after line #75 in indian.py
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'
然后它挂在那里……这是“请按任意键继续”之前的最后一个输出应该出现,但它永远不会.
笔记
我已经采取了第二个脚本并要求它找到“请参考”,它确实如此.不幸的是,然后脚本再次挂起:
p.communicate('\r\n')
再次结束程序,打印错误:
The process tried to write to a nonexistent pipe.
我认为这与this错误有关.
我无法想象我想做的事情是与众不同的.由于这似乎比预期的要复杂一点,我想说我使用的是XP和Python 3.3版本.
解决方法:
像下面这样的东西应该工作:
p = subprocess.Popen([path + '\\' + batchFile, path + '\\' + DIABFile],
bufsize=1, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
while p.poll() is None:
line = p.stdout.readline()
if line.startswith('Press any key to continue'):
p.communicate('\r\n')
标签:python,python-3-x,batch-file,automation
来源: https://codeday.me/bug/20190831/1778474.html