gpt4 book ai didi

python - 如何使用 Popen 同时运行多个具有 while(1) 循环的程序

转载 作者:太空宇宙 更新时间:2023-11-03 21:21:35 24 4
gpt4 key购买 nike

我想用 Popen 运行两个 C 可执行文件。它们都有一个 while(1) 循环,我希望它们同时运行,但我发现这是不行的。

这里有两个 C 可执行文件:

int main(int argc, char *argv[]){
char str1[20];
int i = 0;
while(i < 30){
fprintf(stderr, "hello1\n");
i++;
}
while(1);
}
int main(int argc, char *argv[]){
char str1[20];
int i = 0;
while(i < 30){
fprintf(stderr, "hello2\n");
i++;
}
while(1);
}

这是Python代码:

processes=[subprocess.Popen(program,universal_newlines=True,shell=True) for program in ['./hello1', './hello2']]
for process in processes:
process.wait()

它只打印“hello1”并挂起。

最佳答案

您的 C 代码有一个未引用的变量 str1,仅供引用。但这不是问题。

但是,在使用 Visual C++ 构建 hello1.exehello2.exe 并运行脚本后,我没有收到您的错误,因此它您的问题似乎与您的设置的其他方面有关。

#include "stdafx.h"
#include "stdio.h"

int main(int argc, char *argv[]) {
int i = 0;
while (i < 30) {
fprintf(stderr, "hello[1/2]\n");
i++;
}
while (1);
}

然后这将按您的预期工作:

import subprocess

processes = [subprocess.Popen(program, universal_newlines=True, shell=True) for program in ['hello1.exe', 'hello2.exe']]
for process in processes:
process.wait()

它打印 hello1hello2 各 30 次并等待。

关于python - 如何使用 Popen 同时运行多个具有 while(1) 循环的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54191185/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com