【问题标题】:How to start other script inside a running python script(A new thread or process?) [duplicate]如何在正在运行的python脚本中启动其他脚本(新线程或进程?)[重复]
【发布时间】:2019-11-07 00:03:11
【问题描述】:

如果我有这样的程序:

for i in range (25000):
    do something
    if i == 5000:
        run  new_script.py in a new thread/process
    continue as before 

我该怎么做?

【问题讨论】:

  • 您好,欢迎来到 StackOverflow!如果您还没有,请阅读how to ask。到目前为止,您尝试过什么?
  • if 语法不使用括号,使用双 = 符号进行比较
  • 当标准方法是使用新进程时,为什么要使用 线程 来执行不同的脚本?线程必须共享代码和静态数据,这需要您将其他脚本导入当前进程,而新进程将独立生活。
  • @SergeBallesta:我编辑了我的问题。如果您认为流程是更好的解决方案,请给我一些代码来做到这一点。谢谢。
  • @我把代码从Thread改成了Process,好像没有错误,但是第二个程序不行。

标签: python multithreading


【解决方案1】:

将new_script.py的内容放到一个函数中并导入

from threading import Thread

from new_script import f

for i in range (25000):
    do_something()
    if i == 5000:
        Thread(target=f, args=(arg1, arg2)).start()

【讨论】:

  • 感谢 Politinsa,我尝试了您的代码,但收到此错误消息:Exception in thread Thread-8: Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\ProgramData\Anaconda3\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) TypeError: f() takes 1 positional argument but 10 were given
  • args 是一个元组,其中包含将传递给您的 f 函数的参数。检查f的签名并适配args=(arg1, arg2)
  • 我用过这样的代码Thread(target=f, args=(z)).start()
  • 我编辑了我的问题。请阅读。
猜你喜欢
  • 2023-03-13
  • 2018-01-16
  • 1970-01-01
  • 2011-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多