从python3代码中运行bash脚本的问题

时间:2019-02-01 11:05:00

标签: python linux bash operating-system

我在linux系统上工作。

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

在这些文件夹中,有一个我要运行的python文件 baseFolder / myPython.py      ” folder1 / myBash      ” folder2 / myBash                。                。                。      “ folderN / myBash

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

我使用了操作系统和子进程包:

os.system('shell command')

subprocess.run('shell command')

subprocess.call('shell command')

code1

#!/bin/bash
mkdir myNewFolder

touch myNewFile 

code2

#!/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

1 个答案:

答案 0 :(得分:0)

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