【问题标题】:running bash commands in Python script, can not find other Python modules在 Python 脚本中运行 bash 命令,找不到其他 Python 模块
【发布时间】:2017-03-08 04:30:35
【问题描述】:

标题有点难解释,请看下面:

我用来调用 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 框架的内置函数,例如“训练”和传递参数。训练代码主要使用 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 命令时,它能够启动 train 进程,但是 train 进程调用另一个 python 模块以获取自定义层,但找不到它。 init 和自定义层模块都在同一个文件夹中。

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

【问题讨论】:

    标签: python bash shell


    【解决方案1】:

    每个shell=True subprocess 命令都在一个单独的 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-19
      • 2016-09-27
      • 2020-11-04
      • 1970-01-01
      • 2014-10-04
      相关资源
      最近更新 更多