2017-05-29 57 views
1

我有兩個劇本
1. demo.ksh
2. demo.py如何閱讀變量從shell腳本出口,在python

在demo.ksh我正在導出變量

#!/bin/ksh 
TEST="Hello" 
export TEST 

在我執行demo.ksh並試圖讀取出口值demo.py ..

import os 
import subprocess 
cmd='. demo.ksh' #I even tried 'demo.py' (no .) 
subprocess(cmd,shell=True,stdout=subprocess.PIPE) 
print(os.getenv('TEST')) 
print(os.environ['TEST']) 

我期待

Hello 
Hello 

但要

None 
KeyError: 'TEST' 

雖然這是一個簡單的練習。我無法找到正確的解決方案,請幫我解決我的代碼有什麼問題。

+0

爲什麼你不能使用腳本標準輸出?使用環境變量會很困難,因爲稍微難以獲得另一個進程環境變量。你可以在這裏閱讀更多:https://stackoverflow.com/questions/5905574/how-to-get-the-environment-variables-of-a-subprocess-after-it-finishes-running –

回答

1

導出一個變量使得它可用於衍生shell進程的子進程,但不是父進程(即您的Python程序)。

要獲得預期的輸出嘗試這樣的shell腳本:

#!/bin/ksh 

TEST="Hello" 
export TEST 
python demo.py 

可以改爲通過STDOUT子進程進行通信。爲此,subprocess.check_output可能會有用。