Python subprocess.Popen() 和 Pygame ,如何告诉 Pygame 等待子进程完成 [英] Python subprocess.Popen() with Pygame , how to tell Pygame wait untill subprocess is done

查看:79
本文介绍了Python subprocess.Popen() 和 Pygame ,如何告诉 Pygame 等待子进程完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Pygame 用户太多的主要问题,我想在 Pygame 中接受用户的输入.我可能检查了互联网上的所有信息,包括stackoverflow,都没有解决.

I have a major issue that too many Pygame users has, I want to take input from user in Pygame. I probably check all informations in internet,include stackoverflow, nothing solved.

所以我决定制定一个解决方案,我创建了另一个 Python 脚本(我将其转换为 .exe 以便子进程可以打开它)在 Pygame 运行之前向用户提问,然后该脚本将用户的数据保存到 .txt文件(如数据库).然后在 Pygame 中我打开那个 .txt 文件并获取数据.从理论上讲,它正在工作,但问题是,我必须告诉 Pygame,在子进程正在处理时,等待它.这就是我可以避免 IndexError 等错误的方法.因为我正在使用 readlines() 并且直到 .exe 文件关闭,Pygame 必须等待,如果没有;readlines() 将数据作为 list 给出,它通常会抛出 IndexError.所以 Pygame 必须等到我把数据放在那个 .exe 文件中.让我用我的代码解释一下;

So I decide to make a solution, I created another Python script(I convert it to .exe so subprocess can open it) that asking question to user before Pygame is running, after then that script saving user's data into a .txt file(like a database).Then in Pygame I opening that .txt file and taking the data. Therocially it's working, but problem is, I have to tell Pygame, while subprocess is processing, wait for it. That's how I can dodge errors like IndexError etc. Because I'm using readlines() and untill that .exe file is closed, Pygame has to wait, if not; readlines() giving data as list and it throwing IndexError normally. So Pygame has to wait untill I put the data in that .exe file. Let me explain with my codes;

这是从用户那里获取数据的脚本(我已经将其转换为exe以便子进程可以打开):

This is the script that taking data from user(I converted it to exe already so subprocess can open):

#!/usr/bin/env python
# -*-coding:utf-8-*-

while True:
    user=input("Please enter your name: ")
    try:
        user_age=int(input("Please enter your age: "))
    except ValueError:
        print ("Invalid characters for 'age', try again.")
        continue
    ask_conf=input("Are you confirm these informations?(Y/N): ")
    if ask_conf.lower()=="y":
        with open("informations.txt","w") as f: #create the file
            f.write(user+"\n")
            f.write(str(user_age))
        break
    else:
        continue

然后,在 Pygame 中,我打开了这个 .exe 文件,但 Pygame 不会等待,通常我会收到错误.

And then, in Pygame, I'am opening this .exe file, but Pygame won't wait and normally I'm getting error.

pygame.init()
subprocess.Popen(["wtf.exe"]) #the exe file that taking data from user 
                              #and saving it in "informations.txt"
#codes..
....
....
author = pygame.font.SysFont("comicsansms",25)
with open("informations.txt") as f:
    rd=f.readlines()
author1 = author.render("{}".format(rd[0][0:-1]),True,blue) #Pygame won't wait 
                                                            #so getting IndexError here
age = pygame.font.SysFont("comicsansms",25)
age1 = age.render("{}".format(rd[1]),True,blue)
...
...
...
gameDisplay.blit(author1,(680,15))
gameDisplay.blit(age1,(720,40))

这个方法差不多可以了,我以为我终于在Pygame中得到了这个input问题的解决方案.但是我不知道如何告诉Pygame,等我用完.exe文件,然后处理您的代码.

This method is almost working, I thought finally I got the solution of this input problem in Pygame.But I don't know how to tell Pygame, wait untill I'm done with .exe file, then process your codes.

推荐答案

使用 交流方法:

与进程交互:将数据发送到标准输入.从 stdout 和 stderr 读取数据,直到到达文件结尾.等待进程终止.可选的输入参数应该是要发送给子进程的字符串,如果没有数据应该发送给子进程,则为 None.

Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child.

所以这是执行此操作的代码:

So this is the code to do it:

process = subprocess.Popen(["wtf.exe"])
# block until process done
output, errors = process.communicate()

<小时>

正如@Padraic 所建议的,您可以使用 check_call,这是更多信息 失败时:

try:
    subprocess.check_call([’wtf.exe’])
except subprocess.CalledProcessError:
    pass # handle errors in the called executable
except OSError:
    pass # executable not found

<小时>

另一个选项是调用:

运行 args 描述的命令.等待命令完成,然后返回返回码属性.

Run the command described by args. Wait for command to complete, then return the returncode attribute.

就像这样:

returncode = subprocess.call(["wtf.exe"])

<小时>

并且您也可以使用 wait 如果您不关心数据,只希望返回代码查看是否发生了不好的事情.但是文档说你应该更喜欢 communicate:


And you can also use wait if you don't care about the data and just want the return code to see if something bad happened. But documentation says you should prefer communicate:

警告:当使用 stdout=PIPE 和/或 stderr=PIPE 并且子进程生成足够的输出到管道时,这将导致死锁,从而阻止等待 OS 管道缓冲区接受更多数据.使用communication()来避免这种情况.

Warning: This will deadlock when using stdout=PIPE and/or stderr=PIPE and the child process generates enough output to a pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use communicate() to avoid that.

这篇关于Python subprocess.Popen() 和 Pygame ,如何告诉 Pygame 等待子进程完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆