簡體   English   中英

在 Python 中,如何在正在運行的子進程中引用從“subprocess.run”傳遞的參數?

[英]In Python, how do I reference an argument passed from "subprocess.run" in the subprocess being run?

在我的主函數中,我想將一個變量傳遞給一個子進程,讓子進程對這個變量做一些事情,然后將控制權返回給主進程。

我已經閱讀了幾篇關於將變量(參數)傳遞給子進程的帖子,但是我找不到任何關於在子進程中訪問變量的信息。

這是我正在嘗試做的一個例子。

一個.py

import subprocess

if __name__ == "__main__":

    # Code to generate fn_new

    fn_new = r"path\to\file.ext"    # I want to pass this variable to b.py

    subprocess.run(["python", "b.py", fn_new])    # I read that this is how to pass the var to the subprocess

    # Additional code that depends on fn_new

b.py

print(fn_new)

# NOTE 1: There are several things being done with the variable fn_new
# NOTE 2: I'm not passing anything back to a.py

在 b.py 中,我嘗試from a import fn_new ,但它希望 fn_new 出現在if __name__ == "__main__": in a.py 之外。 我不想將“fn_new”移動到主腳本,因為我必須移動隨之而來的所有處理。

如何在不導入的情況下從 subprocess.run 訪問變量“fn_new”? 還是我以錯誤的方式解決這個問題?

遺憾的是,該變量不會以相同的名稱 (fn_new) 調用。 您可以按位置獲取這里是一個簡單的腳本,可以幫助您入門。

b.py


import sys
print(sys.argv)

暫無
暫無

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

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