Python: OSError: [Errno 2] No such file or directory:

Python: OSError: [Errno 2] No such file or directory:

Have you noticed that you dont get the error if you run

python ./script.py

instead of

python script.py

This is because sys.argv[0] will read ./script.py in the former case, which gives os.path.dirname something to work with. When you dont specify a path, sys.argv[0] reads simply script.py, and os.path.dirname cannot determine a path.

I had this error because I was providing a string of arguments to subprocess.call instead of an array of arguments. To prevent this, use shlex.split:

import shlex, subprocess
command_line = ls -a
args = shlex.split(command_line)
p = subprocess.Popen(args)

Python: OSError: [Errno 2] No such file or directory:

Use os.path.abspath():

os.chdir(os.path.dirname(os.path.abspath(sys.argv[0])))

sys.argv[0] in your case is just a script name, no directory, so os.path.dirname() returns an empty string.

os.path.abspath() turns that into a proper absolute path with directory name.

Leave a Reply

Your email address will not be published. Required fields are marked *