簡體   English   中英

從另一個 Python 文件啟動 Python 文件然后在它們同時運行時通過它們發送數據的最簡單方法是什么?

[英]What is the easiest way to launch a Python file from another Python file then send data across them while they run simultaneously?

我想先運行一個 python 文件(父),它會自動執行另一個 python 文件(子)並將數據(特別是列表)從父文件發送到子文件。

我無法將一個文件導入另一個文件,因為父文件必須執行大量阻塞命令並且我需要子文件連續發布。

我最初嘗試了 Popen 子進程,我可以使用它同時運行這兩個進程,但是我無法從子進程 class 中的父進程中捕獲任何 output。只需將數據寫入文件然后從子進程 class 讀取它就可以了但我無法讓它可靠地工作,因為它只讀了一次; 並關閉文件以再次打開它以閱讀似乎太老套和緩慢了。

那么這通常是如何完成的呢? 這是代碼的超級簡化版本:-

文件 1(父文件):-

list = [0,0,0]
class CmdDecide:
    def __init__(self, param1=50):
        //Some code
        //I tried subprocess.run(['python3',file2.py]) to run the 2 files simultaneously but I need to send the list variable to it
    
    def func_A(self, var_from_someplace_else):
        global list
        list = var_from_someplace_else
        sendList(list)
    
    def sendList(self):
        //Code to send this list to file 2 somehow
    
    //There are a lot more functions in this file

文件 2(子文件):-

def main():
    //Send continuous output [0,0,0] till File 1 changes the array
    //It will continuously output the new array and continue to do so till the program is terminated

注意:Ik this exists 在后台從另一個 Python 代碼運行一個 Python 代碼,但 pipe 尚未實現,我不確定它是否可以處理列表。

如果將兩個文件合並為一個文件的主要問題是阻塞進程,那么將父文件方法作為異步運行 ( https://docs.python.org/3/library/asyncio.html )。 在我看來,將一個文件作為子流程調用並不是 go 轉發的最佳方式,因為它解耦了邏輯但保持了依賴性。 如果您需要將文件作為子進程調用,則查看argpase並將列表作為參數傳遞給

subprocess.run(['python3',file2.py])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM