2017-03-08 89 views
0

這是有點難以在標題解釋,請參閱以下內容:運行bash命令,不能找到其他Python模塊

bash腳本我用來對朱古力函數的調用,這個具體的例子列車採用求解prototxt模型:

#!/bin/bash 

TOOLS=../../build/tools 

export HDF5_DISABLE_VERSION_CHECK=1 
export PYTHONPATH=. 
#for debugging python layer 
GLOG_logtostderr=1 $TOOLS/caffe train -solver lstm_solver_flow.prototxt -weights single_frame_all_layers_hyb_flow_iter_50000.caffemodel 
echo "Done." 

我有很多次都沒有問題的工作。它所做的是使用caffe框架內置的函數,如「train」和傳遞參數。火車代碼主要是用C++構建的,但它爲自定義數據層調用Python腳本。隨着外殼,一切都運行平穩。

現在,我在Python腳本中使用subprocess.call()與殼牌=真

import subprocess 

subprocess.call("export HDF5_DISABLE_VERSION_CHECK=1",shell=True)) 
subprocess.call("export PYTHONPATH=.",shell=True)) 
#for debugging python layer 
subprocess.call("GLOG_logtostderr=1 sampleexact/samplepath/build/tools/caffe train -solver lstm_solver_flow.prototxt -weights single_frame_all_layers_hyb_flow_iter_50000.caffemodel",shell=True)) 

當從一個python腳本(INIT)內運行的bash命令,它是調用這些確切的命令能夠啓動火車過程,但是火車過程會爲另一個自定義圖層的python模塊調用,並且找不到它。 init和自定義圖層模塊都位於同一個文件夾中。

我該如何解決這個問題?我真的需要從Python運行它,以便我可以調試。有沒有辦法讓項目中的-any-python模塊可以從任何來自其他人的調用中訪問?

回答

2

每個shell=Truesubprocess命令被調用單獨的殼。你正在做的是配置一個新的外殼,扔掉它,然後重新開始新的外殼,一遍又一遍。您必須在單個子流程中執行所有配置,但不是很多。

這就是說,你正在做的大部分不是需要的shell。例如,在子進程中設置環境變量可以用Python完成,不需要特殊的導出。例如:

# Make a copy of the current environment, then add a few additional variables 
env = os.environ.copy() 
env['HDF5_DISABLE_VERSION_CHECK'] = '1' 
env['PYTHONPATH'] = '.' 
env['GLOG_logtostderr'] = '1' 

# Pass the augmented environment to the subprocess 
subprocess.call("sampleexact/samplepath/build/tools/caffe train -solver lstm_solver_flow.prototxt -weights single_frame_all_layers_hyb_flow_iter_50000.caffemodel", env=env, shell=True) 

奇是,你甚至不需要shell=True在這一點上,避免它在一般出於安全原因,一個好主意(和次要的性能優勢),所以你可以只是做:

subprocess.call([ 
    "sampleexact/samplepath/build/tools/caffe", "train", "-solver", 
    "lstm_solver_flow.prototxt", "-weights", 
    "single_frame_all_layers_hyb_flow_iter_50000.caffemodel"], env=env)