简体   繁体   中英

Problem to run a bash script from within python3 code

I work with linux system.

I have many different folders, each folder have a bash file (the bash file is equal in each folder). This bash file runs simple commands such as to load an environment, to create files and folders, to run binary applications (for example code1)

Out of these folders there is a python file in wich I want to run baseFolder/myPython.py " folder1/myBash " folder2/myBash . . . " folderN/myBash

PROBLEM: when I run the python script (for example code2) the bash file is not executed inside the folder, it is executed as the bash file were located in the baseFoldes, hence it create folder, files, etc. within baseFolder. I don't understand why.

I used os and subprocess packages:

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") 

Or

subprocess.call(fullPathFolder+"/myBash") 

Or

os.system(fullPathFolder+"/myBash")

baseFolder/myPython.py

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

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

     "     folder1/myBash

     "     folder2/myBash

           .
           .
           .

      "     folderN/myBash

The bash is executed in the folder you started you python script in. You need to change the path using os.chdir() before. Or better: pass the target directory as a parameter to the shell scripts and prepend the path to your file names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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