2017-03-08 91 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)