我在 folder_a 中有一個檔案,我想在 folder_b 中執行一個 bat/bash 檔案。這將與朋友共享,所以我不知道他將從哪里運行該檔案。這就是為什么我不知道確切的路徑。
folder_a
___
| |
| python.py
|folder_b
|___
| |
| bat/bash file
這是我的代碼。它運行沒有錯誤,但它不顯示任何內容。
import os, sys
def change_folder():
current_dir = os.path.dirname(sys.argv[0])
filesnt = "(cd " current_dir " && cd .. && cd modules && bat.bat"
filesunix = "(cd " current_dir " && cd .. && cd modules && bash.sh"
if os.name == "nt":
os.system(filesnt)
else:
os.system(filesunix)
inputtxt = input()
if inputtxt == "cmd file":
change_folder()
我想嘗試只使用內置的 Python 庫。
uj5u.com熱心網友回復:
簡短版本:我相信您的主要問題在于(before each cd。但是,還有其他事情也可以清理您的代碼。
如果您只需要運行正確的批處理/bash 檔案,您可能不必實際更改當前作業目錄。
Python 的內置pathlib模塊可以非常方便地操作檔案路徑。
import os
from pathlib import Path
# Get the directory that contains this file's directory and the modules
# directory. Most of the time __file__ will be an absolute (rather than
# relative) path, but .resolve() insures this.
top_dir = Path(__file__).resolve().parent.parent
# Select the file name based on OS.
file_name = 'bat.bat' if os.name == 'nt' else 'bash.sh'
# Path objects use the / operator to join path elements. It will use the
# correct separator regardless of platform.
os.system(top_dir / 'modules' / file_name)
但是,如果批處理檔案希望它從它自己的目錄運行,您可以像這樣更改它:
import os
from pathlib import Path
top_dir = Path(__file__).resolve().parent.parent
file_name = 'bat.bat' if os.name == 'nt' else 'bash.sh'
os.chdir(top_dir / 'modules')
os.system(file_name)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/401828.html
上一篇:努力使用django顯示影像
