【问题标题】:Problem to run a bash script from within python3 code从 python3 代码中运行 bash 脚本的问题
【发布时间】:2019-06-25 22:54:34
【问题描述】:

我使用的是 linux 系统。

我有很多不同的文件夹,每个文件夹都有一个 bash 文件(每个文件夹中的 bash 文件是相等的)。此 bash 文件运行简单的命令,例如加载环境、创建文件和文件夹、运行二进制应用程序(例如 code1)

在这些文件夹中有一个我想要运行的 python 文件 baseFolder/myPython.py " 文件夹 1/myBash " 文件夹 2/myBash . . . " 文件夹N/myBash

问题:当我运行 python 脚本(例如 code2)时,bash 文件没有在文件夹内执行,它在 bash 文件位于 baseFoldes 中时执行,因此它在 baseFolder 中创建文件夹、文件等. 我不明白为什么。

我使用了 os 和 subprocess 包:

os.system('shell command')

subprocess.run('shell command')

subprocess.call('shell command')

代码1

#!/bin/bash
mkdir myNewFolder

touch myNewFile 

代码2

#!/usr/bin/env python3

import os

import subprocess

... other code ...

subprocess.run(fullPathFolder+"/myBash") 

或者

subprocess.call(fullPathFolder+"/myBash") 

或者

os.system(fullPathFolder+"/myBash")

baseFolder/myPython.py

     "     myNewFolder <<<<<<<<<<?????

     "     myNewFile   <<<<<<<<<<?????

     "     folder1/myBash

     "     folder2/myBash

           .
           .
           .

      "     folderN/myBash

【问题讨论】:

    标签: python linux bash operating-system


    【解决方案1】:

    bash 在您启动python脚本的文件夹中执行的。您需要之前使用os.chdir()更改路径。或者更好:将目标目录作为参数传递给 shell 脚本,并将路径添加到文件名之前。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-30
      • 2013-01-21
      • 1970-01-01
      • 2019-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多