简体   繁体   English

Python/Batch:使用 Python 按任意键继续

[英]Python/Batch: Use Python to press any key to continue

I am using a python script to automate a process involving batch files.我正在使用 python 脚本来自动化涉及批处理文件的过程。 These are batch files that are used for other applications and I am not allowed to edit them.这些是用于其他应用程序的批处理文件,我不允许编辑它们。

At the end of the batch file, it prompts the following:在批处理文件的末尾,它提示以下内容:

"Press any key to continue ..." “按任意键继续……”

How do I use python to recognize when this prompt appears, and how do I respond to it?如何使用python识别何时出现此提示,以及如何响应? I want to be able to close the file so I can run the next batch file.我希望能够关闭该文件,以便我可以运行下一个批处理文件。

Currently I have found the following solution, but it's terrible and makes me feel dirty inside:目前我找到了以下解决方案,但它很糟糕,让我觉得里面很脏:

#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')

Any ideas?有什么想法吗?

Attempt #1尝试 #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')

Resulted in the following output and error:导致以下输出和错误:

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.

The part that seemed weirdest to me was that the startswith first arg must be bytes or a tuple of bytes, not str.对我来说最奇怪的部分是开始的第一个 arg 必须是字节或字节元组,而不是 str。 I looked up the documentation and it definitely should be a string?我查看了文档,它肯定应该是一个字符串? tutorial of startswith 开始教程

So I looked online and found this little bit.于是上网查了一下,发现一点。

The error message seems to be a bug in Python, as it is exactly the other way around.错误消息似乎是 Python 中的一个错误,因为它恰恰相反。 But still, no problems here, add after line #75 in indian.py但是,这里没有问题,在 indian.py 的第 75 行之后添加

try:
    line = line.decode()
except AttributeError:
    pass

And so I did.所以我做到了。

Attempt #2尝试#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

Resulted in the following output:导致以下输出:

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'

And then it hangs there... That is the last output before the "Please press any key to continue" should show up, but it never does.然后它挂在那里......这是“请按任意键继续”之前的最后一个输出,但它永远不会出现。

Notes笔记

I have since taken the second script and asked it to find "Please Refer", which it does.从那以后,我采用了第二个脚本并要求它找到“请参考”,它确实做到了。 Unfortunately, then the script hangs again at the line:不幸的是,脚本再次挂在该行:

p.communicate('\r\n')

Ending the program, again, prints the error:再次结束程序,打印错误:

The process tried to write to a nonexistent pipe.

Which I believe is related to this bug.我认为这与错误有关。

I can't imagine what I'm trying to do is THAT out of the ordinary.我无法想象我正在尝试做的事情与众不同。 Since this is seemingly a little more complicated than expected I would like to say I am using XP and Python version 3.3.由于这似乎比预期的要复杂一些,我想说我使用的是 XP 和 Python 3.3 版。

Something like the following should work:像下面这样的东西应该工作:

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')

You could parse the output of the subprocess and match on the "Press any key to continue" phrase to continue on.您可以解析子流程的输出并匹配“按任意键继续”短语以继续。

See this thread: read subprocess stdout line by line especially what he posted as Update2请参阅此线程: 逐行读取子进程标准输出,尤其是他作为 Update2 发布的内容

It might look like this:它可能看起来像这样:

import subprocess
proc = subprocess.Popen([path + '\\' + batchFile, path + '\\' + DIABFile],stdout=subprocess.PIPE)

for line in iter(proc.stdout.readline,''):
    if (line.rstrip() == "Press any key to..":
        break;

As stated in the OP, none of the solutions were solving the problem.正如 OP 中所述,没有一个解决方案可以解决问题。 So at the end the solution from Bryce solved the problem for me:所以最后布莱斯的解决方案为我解决了这个问题:

subprocess.call([path + '\\' + batchFile, path + '\\' + DIABFile], stdin=subprocess.DEVNULL)

The solution from this post worked for me: 这篇文章中的解决方案对我有用:

Try to execute cmd.exe /c YourCmdFile < nul尝试执行cmd.exe /c YourCmdFile < nul

YourCmdFile - full path to your batch script YourCmdFile - 批处理脚本的完整路径

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM