如何在切换上下文之前强制python命令一起运行?

如何在切换上下文之前强制python命令一起运行?,python,multiprocessing,Python,Multiprocessing,我有两个进程正在运行,每个进程都在打印自己的配置文件。配置文件没有我可以跟踪的唯一数据,因此我无法知道哪个进程打印了什么 我的处理方法是添加前缀打印: def print_config(proc_name): print(proc_name) print_conf() # both processes are given the target print_config, # args='a' or 'b', and then are started 但是,操作系统按以下顺序排

我有两个进程正在运行,每个进程都在打印自己的配置文件。配置文件没有我可以跟踪的唯一数据,因此我无法知道哪个进程打印了什么

我的处理方法是添加前缀打印:

def print_config(proc_name):
    print(proc_name)
    print_conf()

# both processes are given the target print_config,
# args='a' or 'b', and then are started
但是,操作系统按以下顺序排列命令:

1. Proc A: print(proc_name)
2. Proc B: print(proc_name)
3. Proc ?: print_conf()
4. Proc ??: print_conf()

如何组合打印,以便查看printproc_名称,并在打印配置之后立即查看?

您可以使用锁对象来控制线程的执行。基本上,其原理是在打印之前锁定全局对象,并在打印完成后释放它,以便其他线程可以访问它并依次锁定它并自行进行打印。以下是其中一个例子:

更新:

此外,如果您不询问锁定线程,那么实际上操作两个独立脚本的输出,概念是完全相同的,只是您可以使用lock file来实现这一目的。假设您有两个非常相似的脚本: 第一个:

import os.path

while(os.path.exists("lock.LCK")):
        continue


f = open("lock.LCK", "w+")
file_for_output = open("output.txt", "a")
file_for_output.write("Hi2\n")
file_for_output.write("There2\n")
f.close()
os.remove("lock.LCK")
file_for_output.close()
还有一个:

import os.path

while(os.path.exists("lock.LCK")):
        continue


f = open("lock.LCK", "w+")
file_for_output = open("output.txt", "a")
file_for_output.write("Hi1\n")
file_for_output.write("There1\n")
f.close()
os.remove("lock.LCK")
file_for_output.close()

如果您同时运行这两个文件,则由于死while循环中的锁定文件保护,1将不得不等待另一个文件完成写入。请注意,这只是处理此问题的基本示例。如果您想在实际代码中实现这一点,我建议您为死循环和适当的异常设置超时限制。

您有两个进程,但它们共享相同的标准输出?或者这些进程写入同一个文件?它们都写入同一个FD。根据您在评论和编辑问题中提供的其他信息,我在回答中添加了更多信息。
import os.path

while(os.path.exists("lock.LCK")):
        continue


f = open("lock.LCK", "w+")
file_for_output = open("output.txt", "a")
file_for_output.write("Hi1\n")
file_for_output.write("There1\n")
f.close()
os.remove("lock.LCK")
file_for_output.close()