[英]Bash can't find right directory in script
我正在為文本編輯器制作一個壓縮腳本,所有這些工作都在使文件Run
所需的部分進行。 Run內只有以下代碼: python ./App.pyc
。 當我在Finder中雙擊運行該程序時,它說它can't open file './App.pyc' [Errno 2] No such file or directory
Terminal中can't open file './App.pyc' [Errno 2] No such file or directory
。
而且,如果我將其cd
到目錄Run
並且App.pyc
在其中之后,通過Terminal運行它,則它可以工作。 我假設這是因為我們不在正確的目錄中。
我的問題是,如何確定Run
在正確的目錄中? 如果我將cd
放入其中,它將起作用,但是如果有人將文件夾移至其他位置,它將不再起作用。
#!/usr/bin/python
### Compresser script.
# Compress files.
import App
import Colors
# Import modules
import os
# Clear the folder to put the compressed
# files in (if it exists).
try:
os.system('rm -rf BasicEdit\ Compressed')
except:
pass
# Remake the folder to put compressed files in.
os.system('mkdir BasicEdit\ Compressed')
# Move the compiled files into the BasicEdit
# Compressed folder.
os.system('mv App.pyc BasicEdit\ Compressed/')
os.system('mv Colors.pyc BasicEdit\ Compressed/')
# Create contents of run file.
run_file_contents = "python ./App.pyc\n"
# Write run file.
run_file = open("./BasicEdit Compressed/Run", 'w')
run_file.write(run_file_contents)
# Give permissions of run file to anybody.
os.system('chmod a+x ./BasicEdit\ Compressed/Run')
# Finally compress BasicEdit, and remove the old
# folder for BasicEdit Compressed.
os.system('zip -9r BasicEdit.zip BasicEdit\ Compressed')
os.system('rm -rf BasicEdit\ Compressed')
(PS, [Errno 1]
什么?我以前從未見過。)
可以使用os.chdir()
調用修改Python腳本的當前工作目錄,然后引用.
將是正確的。
如果要查找當前正在運行的源文件的位置,而不是對目錄進行硬編碼,則可以使用:
os.chdir(os.path.dirname(__file__))
相當於此邏輯的bash為:
cd "${BASH_SOURCE%/*}" || {
echo "Unable to change directory to ${BASH_SOURCE%/*}" >&2
exit 1
}
有關更多詳細信息和注意事項,請參見BashFAQ#28 。
正如上面與@William Purcell一起開發的那樣,您必須通過 os.pwd()
檢索絕對路徑,然后將絕對路徑用於python調用。
我撤回提案,並接受@Charles Duffy的回答。 但是,我不會刪除我的嘗試,因為這些評論似乎對其他人有用!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.