在Python脚本中运行bash命令时,找不到其他Python模块

在Python脚本中运行bash命令时,找不到其他Python模块,python,bash,shell,Python,Bash,Shell,标题中有点难以解释,请参见以下内容: 我用来调用caffe函数的bash脚本,此特定示例使用solver 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

标题中有点难以解释,请参见以下内容:

我用来调用caffe函数的bash脚本,此特定示例使用solver 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”和pass参数。列车代码主要是用C++构建的,但它调用Python脚本来定制数据层。有了外壳,一切都运转顺畅

现在,我在python脚本中使用subprocess.call()调用这些精确的命令,Shell=True

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命令时,它能够启动train进程,但是train进程调用另一个python模块以获取自定义层,并且找不到它。init和自定义层模块都位于同一文件夹中


我如何解决这个问题?我真的需要从Python运行它,这样我就可以调试了。是否有一种方法可以使项目中的-any-python模块对其他任何调用都是可访问的?

每个
shell=True
子流程
命令都在单独的shell中调用。你要做的是配置一个新的shell,扔掉它,然后重新开始一个新的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)