0

I have two python files in the same directory.

File 1: main.py

import time
import threading
from subprocess import call

def thread_second():
    call(["python", "python_test.py"])
processThread = threading.Thread(target=thread_second)  # <- note extra ','
processThread.start()

time.sleep(2)

print ('the file is running in the background')

print('exit main')

File 2: secondary.py

import time
import os

try:
    file = open("runnnig.tmp","x")
    file.close()
except Exception as FileExistsError:
     print('file already exists')

print('Secondary file is running')

# do some staff 
time.sleep(10)

What I am trying to accomplish is to run the secondary.py from main.py. Only one problem I want the secondary.py to run completely independent of the main.py so that after opening the secondary.py the main.py exits. With this solution here, that I found here the secondary.py starts running normally but the main.py hangs until the secondary.py exits. How can I accomplish that?


PS. For anyone wondering what I am trying to do

I have a node.js server running on a Raspberry pi. When a request is given to the server the main.py is called from the server. The secondary.py is a script that tells raspberry to start logging values from a sensor. The secondary.py will run an infinite loop until another script interrupts it. That's why I don't want the main.py to hang until the secondary.py exits

  • You can use `nohup &` to detach the subprocess and run it in the background. No need for a thread in `main.py`. – 0x5453 Jul 17 '20 at 12:57
  • @0x5453 How can I do that from the main.py? All I can find regarding ```nohup``` is how to run a script from the terminal. What I want is to "call" the script from the main.py – Kyriafinis Vasilis Jul 17 '20 at 13:03

1 Answers1

1

You don't need threading for that, and using Popen instead of call means that your main.py doesn't wait on the new process to end.

import time
from subprocess import Popen

Popen(["python", "python_test.py"])

time.sleep(2)

print ('the file is running in the background')

print('exit main')
Jasmijn
  • 9,370
  • 2
  • 29
  • 43
  • Works great only one question. Is there any way to see the output of the secondary.py in the console? – Kyriafinis Vasilis Jul 17 '20 at 21:13
  • 1
    You should be able to do that with the `stdout` parameter to `Popen`: https://docs.python.org/3/library/subprocess.html#frequently-used-arguments For a long-running process it might be a good idea to send it to a file so you can check it with a command like `tail -f` – Jasmijn Jul 18 '20 at 22:28