![](/img/trans.png)
[英]How do I run a bash script inside Python, but act as if it's running from another directory?
[英]How do I find directory of the Python running script from inside the script?
如何在Python [3.3]中找到正在運行的Python腳本的目錄? 我嘗試了以下建議: 如何使用Python查找腳本的目錄? ,但我得到“語法無效”並指向“os”(我確實導入了os)。
我得到答案的最接近的是:sys.argv [0],但仍然包含文件名,所以我不能使用它。 還有其他方法嗎?
注意:我對Python很新。
這是我到目前為止所做的一些代碼(它表示rundir = sys.argv [0]的部分是建議的代碼所在的部分):
import pygame
from pygame.locals import *
import os, sys
import time
pygame.init()
import statuscheck
print("Completed program status check.")
import mods.modlist
print("Loaded all mods..")
print("Completed loading")
sys.dont_write_bytecode = True
rundir = sys.argv[0]
print("Running from" + rundir)
要獲取包含您正在運行的模塊的目錄:
import os
path = os.path.dirname(os.path.realpath(__file__))
或者,如果您想要從中調用腳本的目錄:
import os
path = os.getcwd()
來自文檔 :
__file__
是從中加載模塊的文件的路徑名(如果是從文件加載的)。
根據腳本的調用方式,這可能是os.getcwd()
的相對路徑,因此os.path.realpath(__file__)
會將其轉換為絕對路徑(或者什么也不做__file__
已經是絕對路徑) 。 然后os.path.dirname()
將通過剝離文件名返回完整目錄。
試試這個:
import os
os.path.dirname(__file__)
__file__
獲取您所在文件的名稱dirname
函數獲取文件所在的目錄。
語法錯誤可能與print語句有關。 在python 3.x中
print "hi"
是無效的。 打印現在是一個功能。
print("hi")
作品。 你需要括號。
這應該工作:
import os,sys
print(os.path.dirname(os.path.realpath(sys.argv[0])))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.