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

2
  • You can use nohup <cmd> & to detach the subprocess and run it in the background. No need for a thread in main.py. Commented Jul 17, 2020 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 Commented Jul 17, 2020 at 13:03

1 Answer 1

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')
Sign up to request clarification or add additional context in comments.

2 Comments

Works great only one question. Is there any way to see the output of the secondary.py in the console?
You should be able to do that with the stdout parameter to Popen: docs.python.org/3/library/… 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.