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

时间:2017-03-08 04:30:35

标签: python bash shell

标题中有点难以解释,请参阅下文:

我用来调用caffe函数的bash脚本,这个特定的例子使用求解器原型训练模型:

#!/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脚本。有了shell,一切都顺利进行。

现在,我使用带有Shell = True

的subprocess.call()在python脚本中调用这些确切的命令
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模块可以被其他人调用?

1 个答案:

答案 0 :(得分:2)

单独的 shell中调用每个shell=True subprocess命令。你正在做的是配置一个新的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,出于安全原因(以及较小的性能优势),一般来说避免它是个好主意,所以你可以这样做: / p>

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)