简体   繁体   中英

Bash can't find right directory in script

I'm making a compress script for my text editor, and it's all working up to the part where it needs to make the file Run . Inside of Run is just this code: python ./App.pyc . When I run the program by double-clicking on it in Finder, it says that it can't open file './App.pyc' [Errno 2] No such file or directory within Terminal.

And if I run it through Terminal after I've cd 'd to the directory Run and App.pyc are in, it works. I'm assuming this is because we aren't in the right directory.

My question is, how can I make sure Run is being ran in the right directory? If I put cd in it, it'll work, but then if somebody moves the folder elsewhere it won't work anymore.


#!/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, what's [Errno 1] ? I've never seen it before.)

The Python script's current working directory can be modified with the os.chdir() call, after which references to . will be correct.

If you want to find the location of the source file currently being run rather than hardcoding a directory, you can use:

os.chdir(os.path.dirname(__file__))

The bash equivalent to this logic is:

cd "${BASH_SOURCE%/*}" || {
  echo "Unable to change directory to ${BASH_SOURCE%/*}" >&2
  exit 1
}

See BashFAQ #28 for more details and caveats.

As developed above together with @William Purcell, you have to retrieve the absolute path by os.pwd() and then use the absolute path for the python call.

I withdraw my proposal and go with @Charles Duffy's answer. However, I don't delete my attempt as the comments seem to be useful to others!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM