使用 os.popen() 或 subprocess 来执行函数

Using os.popen() or subprocess to execute functions

我目前正在研究线程、多进程和 os 文档以改进我的程序的结构。然而,老实说,其中一些很复杂,我无法在我的程序中实现它,要么由于 Whosebug 而崩溃,要么输入错误,要么根本没有输出。所以这是我的问题。

假设我有一个传递给函数的名称列表,并且该函数是我想要在另一个控制台中 运行 使用的 - 当然是 python 解释器。并将它 运行 放在一个完整的循环中。

假设我有这个:

def execute_function(name, arg1, arg2):
   While True:
       #do something

for name in names:
   execute_function(name, arg1, arg2)

我应该使用什么才能 运行 这个函数以编程方式在 python 和 运行 上打开另一个控制台 While True: 是 subproccess/multiprocess/threading或者 os.popen()?

在这个例子中,我应该如何执行?多处理池和进程总是和我一起崩溃。所以我认为这不是正确的解决方案。到目前为止,从我搜索的内容来看,我还没有看到线程和子进程与函数一起使用的示例。有解决方法吗?或者我可能错过了一个简单的解决方案?谢谢。

编辑:

类似代码:

     if symbols is not None and symbols1 is not None:

         symbols = [x for x in symbols if x is not None]
         symbols1 = [x for x in symbols1 if x is not None]
         if symbol != None and symbol in symbols and symbol in symbols1:
              with Pool(len(exchanges)) as p:
                   p.map(bot_algorithm, (a, b, symbol, expent,amount))

http://prntscr.com/j4viat - 错误看起来像什么

subprocess 总是 通常优于 os.system().

文档包含许多示例 - 在您的情况下,如果您想查看命令的结果,您的 execute_function() 函数可能需要使用 subprocess.check_output()

例如:

def execute_function(name, arg1, arg2):
  output = subprocess.check_output(["echo", name])
  print(output)

虽然这只是启动一个新进程,并等待它 return。虽然这在技术上是两个进程,但它并不是您所谓的多线程。

要同步使用 运行 多个子进程,您可以对多处理库执行类似这样的操作:

from multiprocessing.dummy import Pool

def execute_function(name, arg1, arg2):
  return subprocess.check_output(["echo", name])

names = ["alex", "bob", "chrissy"]

pool = Pool()

map_results = pool.map(execute_function, names)

这将一个迭代器(名称列表)映射到一个函数 (execute_function) 并且 运行 一次将它们全部映射。好吧,你的机器同时拥有多少内核。 map_results 是来自 execute_function 函数的 return 个值的列表。