Search code examples
pythondjangocommandpython-unittestdjango-unittest

Python (django) call two management commands at the same time


enter image description hereI'm writing unit tests for my management commands. I would like to run my two management commands meanwhile by using call_command() function. How can I do that? I need to run them at the same time because they do work together, one creates data and the other uses that data.


Solution

  • While I certainly don't think this is the right approach, the correct way two run two things "simultaneously" in Python is by using threads.

    The following code will launch two threads, each running their own management command.

    from threading import Thread
    
    def function1():
        call_command('fake')
    
    def function2():
        call_command('engine')
    
    thread1 = Thread(target=function1)
    thread2 = Thread(target=function2)
    
    thread1.start() # returns immediately
    thread2.start() # returns immediately
    
    import time
    time.sleep(3600) # now we wait...
    

    A better approach would be to try to create a single management command that does what you need, so threads aren't needed. You will find that using threads, especially as a beginner, will make things needlessly complicated.