[英]Python 2.7 read exported variables from bash
我有一個python2.7腳本正在調用bash腳本,在bash腳本中我正在導出2個我已經嘗試過的declare -x
帶有declare -x
和export
變量,然后我試圖使用以下命令在python腳本中讀取此變量os.getenv
和我也嘗試使用os.environ
但每次都得到None
類型。 這是我的腳本的片段:
蟒蛇:
def set_perforce_workspace():
global workspace_path
global workspace_root_path
script_path = "somePath"
depot_name = "TestingTools"
dir_to_download = "vtf"
bash_command = "./createWorkspace.sh " + "-d " + depot_name + " -w " \
+ PerforceUtils.WORKSPACE_NAME + " -a " + dir_to_download
print bash_command
print os.getcwd()
try:
os.chdir(script_path)
except OSError as e:
print "Error: {0}".format(e)
print os.getcwd()
return_code = call([bash_command], shell=True)
test = os.getenv("workspace_path")
print "this is test {0}".format(test)
workspace_path = os.getenv("workspace_path")
workspace_root_path = os.getenv("workspace_root_path")
print "This is the return code {0}".format(return_code)
print "this is the workspace path: {0}".format(workspace_path)
print "this is the workspace root path: {0}".format(workspace_root_path)
return return_code
重擊:
declare -x workspace_root_path="$workspaceProjPath"
export workspace_path="$workspaceProjPathLocal"
從os.environ
的文檔中:
首次導入os模塊時(通常是在Python啟動期間作為處理site.py的一部分)捕獲了此映射。 此時間之后對環境所做的更改不會反映在os.environ中,除非直接通過修改os.environ進行更改。
因此,基本上,當您的bash腳本更改環境然后返回到python腳本時,不會刷新環境變量。 真煩人。 正如文檔所說,最好的解決方案是將變量直接添加到環境列表中,例如:
os.environ['PATH'] = '/bin/'
如何完成此操作取決於您,管道是一種相當不錯的方法。 盡管煩人。 不幸的是,沒有辦法“刷新”環境列表。 在許多情況下,最好只是刪除bash腳本並以某種方式使其適應python腳本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.