Run two python files at the same time

前端 未结 4 1759
遥遥无期
遥遥无期 2021-01-13 23:25

I have tried using

#!/bin/bash
python ScriptA.py &
python ScriptB.py &

to run both scripts at the same time but it always returns

相关标签:
4条回答
  • 2021-01-14 00:00

    You have to import os module and use the system function from it, then separate the two Python files you are running by &&.

    import os
    def song():
        user = input()
        if user == "Chance":
            os.system('python ScriptA.py && python ScriptB.py')
        else:
            print("Error")
    
    song()
    

    But I will advice you to just import the two files you want to run into the third file and just run the functions in there like normal functions.

    e.g.

    import ScriptA
    import ScriptB
    
    ScriptA.function()
    ScriptB.function()
    

    If there are no functions inside the scripts, the script runs immediately after they are imported.

    0 讨论(0)
  • 2021-01-14 00:06

    You can just open both files on the python IDLE and run each o them. If you need both files to run simultaneously (the first way you have the delay of pressing F5 on each file) you can use PyCharm and download the multirun plugin.

    0 讨论(0)
  • 2021-01-14 00:08

    You can try os.system :

    import os
    
    os.system("python ScriptA.py &")
    os.system("python ScriptB.py &")
    
    0 讨论(0)
  • 2021-01-14 00:10

    I think you are looking for multi-threading

    you could merge your both script into another script, then lauch them using theads

    --edit--

    from threading import Thread
    
    import cv2
    import numpy as np
    import os
    from playsound import playsound
    
    def play_sound(): 
        # import your script A
        a = (r"C:\Users\A\Desktop\sound.mp3")
        playsound(a)
    
    def CV2_stuff():
        # import your script B
        os.environ['SDL_VIDEO_CENTERED'] = '1'
        cap = cv2.VideoCapture("video.mp4")
        ...
    
    
    Thread(target = play_sound).start() 
    Thread(target = CV2_stuff).start()
    

    hope it helps

    this could work too

    import ScriptA
    import ScriptB
    
    ScriptA.function()
    ScriptB.function()
    

    but they wouldn't be exectuted in the same time

    0 讨论(0)
提交回复
热议问题