【问题标题】:run multiple shell command that depend on the first one (dir_path)运行依赖于第一个的多个 shell 命令(dir_path)
【发布时间】:2020-02-29 16:42:57
【问题描述】:

我正在尝试使用 subprocess.run 来构建我的 CMake 项目,但代码完成时没有错误,但它无法正常工作。

代码是:

import subprocess

git_repo_remvoe_destination = '/home/yaodav/Desktop/'
git_repo_clone_destination = git_repo_remvoe_destination + 'test_clone_git'
test_path = git_repo_clone_destination + "/test/"
cmake_debug_path = test_path + "cmake-debug-build"
cmake_build_command = " cmake -Bcmake-build-debug -H. -DCMAKE_BUILD_TYPE=debug -DCMAKE_C_COMPILER=/usr/local/bin/gcc " \
                      "-DCMAKE_CXX_COMPILER=/usr/local/bin/c++ -Bcmake-build-debug -H. " \
                      "-DSYTEM_ARCH=x86_64-pc-linux-gnu-gcc-7.4.0"
cmake_link_command = "cmake --build cmake-build-debug --target all"

cmake_command = ['cd '+test_path, cmake_build_command, cmake_link_command]

out = subprocess.run(cmake_command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)

我尝试了this 的回答,但没有成功

我该怎么做?

【问题讨论】:

    标签: python python-3.x subprocess


    【解决方案1】:

    2 个问题。

    首先,您应该为每个命令调用一次subprocess.run(),而不是将三个不同的命令放在一个列表中。

    第二:cd ...命令只是改变了一个子进程中的当前工作目录,连续的命令将不再在同一目录中。

    但是有一个简单的解决方案。

    subprocess.run 有一个 cwd 参数 (https://docs.python.org/2/library/subprocess.html#popen-constructor),允许您指定应在其中执行子进程的目录。

    所以下面应该这样做:

    out = subprocess.run(cmake_build_command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=test_path, shell=True)
    out += subprocess.run(cmake_link_command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=test_path, shell=True)
    

    【讨论】:

      猜你喜欢
      • 2012-08-20
      • 2015-02-24
      • 2011-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-23
      • 2023-03-24
      相关资源
      最近更新 更多