繁体   English   中英

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

[英]running bash commands in Python script, can not find other Python modules

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

我用来调用caffe函数的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脚本。 有了外壳,一切都能顺利进行。

现在,我在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模块的自定义层,但找不到它。 初始化和自定义层模块都在同一文件夹中。

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

每个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 ,并且出于安全原因(以及次要的性能优势),通常避免使用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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM