1

If I have a program like this:

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

How can I do this?

Hasani
  • 3,543
  • 14
  • 65
  • 125
  • Hello, welcome to StackOverflow! If you already haven't, please read [how to ask](https://stackoverflow.com/help/how-to-ask). What have you tried until this point ? –  Jun 25 '19 at 07:43
  • 1
    The `if` syntax does not use parentheses and use double `=` signs for comparison – politinsa Jun 25 '19 at 07:56
  • 1
    Why do you want to use a *thread* to execute a different script when the standard way is to use a new process? A thread has to share the code and static data, which will require that you import the other script into your current process, while a new process will live its life independantly. – Serge Ballesta Jun 25 '19 at 08:04
  • @SergeBallesta: I edited my question. If you think process is a better solution please give me some codes to do that. Thanks. – Hasani Jun 25 '19 at 08:23
  • @I changed the code from `Thread` to `Process` and seems there is no errors, but the second program doesn't work. – Hasani Jun 25 '19 at 17:37

1 Answers1

1

Put the content of new_script.py in a function and import it

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
  • 3,480
  • 1
  • 11
  • 36
  • Thanks Politinsa, I tried your code but got this error message: `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` – Hasani Jun 25 '19 at 08:20
  • `args` is a tuple containing the argument that will be passed to your `f` function. Check the signature of `f` and adapt `args=(arg1, arg2)` – politinsa Jun 25 '19 at 11:19
  • I used a code like this `Thread(target=f, args=(z)).start() ` – Hasani Jun 25 '19 at 17:13
  • I edited my question. please read. – Hasani Jun 25 '19 at 17:21