如何使用 Python 运行程序数百次?

发布于 2024-12-19 00:19:23 字数 132 浏览 0 评论 0原文

我有一个程序,需要使用不同的值调用 100 多次。

我想同时执行此操作,而不是等待一个调用完成然后再次开始。

我怎样才能实现它?

多线程是解决这个问题的方法。

我正在使用 python。

I have a program which I need to call more than 100 times with different values.

I want to do it simultaneously that is not wait for one call to complete and then to start again.

How can I achieve it ?

Is multithreading the solution to it.

I am using python for it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

笑梦风尘 2024-12-26 00:19:23

您可以使用 subprocess 模块来完成此操作。下面是一个运行 sleep 命令一百次的示例,睡眠值在 0 到 10 秒之间。它并行运行它们,然后在它们全部完成时退出。

import subprocess
import time

bin_path = 'sleep'
invocation_args = [[str(x*0.1)] for x in range(0,100)]

subprocs = []
for args in invocation_args:
    subprocs.append(subprocess.Popen([bin_path] + args))

while len(subprocs) > 0:
    subprocs = [p for p in subprocs if p.poll() is None]
    time.sleep(0.05)

print 'Finished running all subprocs'

You can do this with the subprocess module. Here is an example that runs the sleep command a hundred times, with a sleep value between 0 and 10 seconds. It runs them all in parallel and then exits when they all finish.

import subprocess
import time

bin_path = 'sleep'
invocation_args = [[str(x*0.1)] for x in range(0,100)]

subprocs = []
for args in invocation_args:
    subprocs.append(subprocess.Popen([bin_path] + args))

while len(subprocs) > 0:
    subprocs = [p for p in subprocs if p.poll() is None]
    time.sleep(0.05)

print 'Finished running all subprocs'
那请放手 2024-12-26 00:19:23

您可以尝试 pyCUDA。它使用多线程并在 NVIDIA 的 GPU 上运行。

You could try pyCUDA. It uses multithreading and runs on NVIDIA's GPU's.

假情假意假温柔 2024-12-26 00:19:23

正如评论所指出的,这实际上可能不是实现您的目标的最佳方式,具体取决于您的目标是什么。

但是,如果您决定这样做,请查看子流程 Python 模块。您将需要直接使用 Popen 而不是 call 之类的便利函数,因为便利函数将等待被调用的进程结束。

或者,您可以使用带有 P_NOWAIT 选项的 os.spawn ,但 Popen是优选的。

As the comments point out, this may not actually be the best way to achieve your goal, depending on exactly what your goal is.

However, if you decide you want to do it this way, look at the subprocess module for Python. You will need to directly use Popen rather than the convenience functions like call since the convenience functions would wait for the called process to end.

Alternatively, you could use os.spawn with a P_NOWAIT option, but Popen is preferred.

黑凤梨 2024-12-26 00:19:23

如果您需要进行某种压力/负载测试,那么现有的开源解决方案可能更合适,例如 jMeter (java) 或 TheGrinder(带有 Jython 脚本的 Java)。

If you need this for some kind of stress/load testing maybe existing open-source solutions would be more appropriate, e.g. jMeter (java) or TheGrinder (Java with scripts in Jython).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文