我想用一個腳本main.py呼叫另外一個腳本run.py
# main.py
import subprocess
import sys
def fn():
print('I am fn...')
fpath = '/Users/runtest/run.py'
def run_with_exec():
'''以exec運行'''
with open(fpath, 'r', encoding="utf8") as f:
code = f.read()
exec(compile(code.encode("utf-8"), fpath, 'exec'), globals())
def run_with_subprocess():
'''以subprocess方式運行'''
subprocess.run([sys.executable, fpath]) # Just run the program
if __name__ == "__main__":
run_with_exec()
run_with_subprocess()
用run_with_exec()運行可以把globals()傳進去,被呼叫的腳本run.py就可以使用
main.py中的fn函式
但是用 run_with_subprocess()運行,怎樣才能讓被呼叫的腳本run.py能使用main.py中的fn函式呢?
有沒有大神幫忙看下,萬分感謝!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/139531.html
