简体   繁体   English

如何同时运行多个python命令?

[英]How to run multiple python commands at the same time?

I've read that subprocess should be used but all the examples i've seen on it shows that it runs only command-line commands. 我已经读过应该使用子流程,但是我在上面看到的所有示例都表明它仅运行命令行命令。 I want my program to run a python command along with another command. 我希望我的程序与另一个命令一起运行python命令。 The command i want to run is to send an email to a user while a user plays a game i created. 我要运行的命令是在用户玩我创建的游戏时向用户发送电子邮件。 i have to have the python commands run at the same time because without doing so nothing else in the game can happen before the email is finished sending so it lags the game. 我必须同时运行python命令,因为如果不这样做,那么在电子邮件发送完毕之前,游戏中的其他任何事情都不会发生,因此会滞后于游戏。 Please help and any input is appreciated. 请帮助,我们将不胜感激。

听起来您正在寻找线程,这是一个相对较深的主题,但这应该可以帮助您入门: http : //www.devshed.com/c/a/Python/Basic-Threading-in-Python/

Threading is talked about in another answer, but you can get basically what you want by using subprocess's Popen command: http://docs.python.org/library/subprocess.html#subprocess.Popen 在另一个答案中讨论了线程,但是您可以通过使用子进程的Popen命令基本获得所需的内容: http : //docs.python.org/library/subprocess.html#subprocess.Popen

What you'll basically want is this (assuming proc is initialized somewhere in the game loop): 您基本上想要的是这个(假设proc在游戏循环中的某个地方初始化了):

#...game code here...

args = [command_name_as_string, arg_1_to_command, arg_2_to_command, etc.]
proc = subprocess.Popen(args)

Then, you'll go back to your game loop. 然后,您将回到游戏循环。 At some point in the game loop, you can put in something like this: 在游戏循环中的某个时刻,您可以输入以下内容:

if proc:
    proc.poll()
    if proc.returncode:
        #...do whatever you want with the process output here, which can 
        # be accessed with proc.stdin, proc.stderr, and so on...
    proc = None

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

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