簡體   English   中英

從python3代碼中運行bash腳本的問題

[英]Problem to run a bash script from within python3 code

我使用linux系統。

我有許多不同的文件夾,每個文件夾都有一個bash文件(bash文件在每個文件夾中都相等)。 這個bash文件運行簡單的命令,例如加載環境,創建文件和文件夾,運行二進制應用程序(例如code1)。

在這些文件夾中,有一個python文件,我想運行baseFolder / myPython.py“ folder1 / myBash” folder2 / 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

在bash在文件夾執行你的,你需要改變使用路徑開始你的python腳本os.chdir()之前。 或更妙的是:將目標目錄作為參數傳遞給Shell腳本,並在路徑前添加文件名。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM