简体   繁体   English

Python 在 for 循环中的 os.system:如何在重新启动循环之前等待命令完成?

[英]Python's os.system within a for loop: how to wait for a command to finish before re-starting the loop?

I am new in using os.system (in Python 3) and am trying to execute a program that I would normally run in a Linux terminal.我是使用 os.system(在 Python 3 中)的新手,并且正在尝试执行一个我通常会在 Linux 终端中运行的程序。 I need to iterate a few times and am using something like the following loop:我需要迭代几次并使用类似以下循环的东西:

for item in item_list:
    os.system("gnome-terminal -- program_execute "+item) 

The problem is that this loop simutaneously opens n terminal windows (the length of my item_list is n ) and executes all of them at the same time.问题是这个循环同时打开n终端窗口(我的item_list的长度是n )并同时执行所有这些。 My question is:我的问题是:

How could I run the loop len(item_list) times with the next run starting only after the current one finishes?我怎么能运行循环len(item_list)次,只有在当前运行完成后才开始下一次运行?

I can't use sleep() because the running time varies from item to item and I would like to optimize the process.我不能使用sleep()因为运行时间因项目而异,我想优化该过程。

EDIT: I've tried using .communicate() and .wait() without success.编辑:我试过使用 .communicate() 和 .wait() 没有成功。 I would like os.system (or os.subprocess) to understand that the gnome-terminal is still running, only passing by the next element in the loop after gnome-terminal from previous loop has closed.我希望 os.system(或 os.subprocess)了解 gnome-terminal 仍在运行,只有在上一个循环的 gnome-terminal 关闭后才通过循环中的下一个元素。

I used subprocess with the code below and it worked, ie the software runs once and finishes completely before going to the next loop.我在下面的代码中使用了 subprocess 并且它起作用了,即软件运行一次并在进入下一个循环之前完全完成。

for item in item_list:
    subprocess.call(["gnome-terminal","--disable-factory","--","my_command"])

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

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