[英]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.