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

放肆的年华 提交于 2019-12-17 15:40:07

问题


I have a 100 lines, 3 years old python scraper that now bug. Starting lines are:

import urllib, re, os, sys, time    # line 1: import modules
os.chdir(os.path.dirname(sys.argv[0])) # line 2: all works in script's folder > relative address
# (rest of my script here!)

When run,

$cd /my/folder/
$python script.py

I receive the error:

python script.py 
Traceback (most recent call last):
  File "script.py", line 2, in <module>
    os.chdir(os.path.dirname(sys.argv[0]))
OSError: [Errno 2] No such file or directory: ''

How should I read this error and what to do ?


回答1:


Have you noticed that you don't 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 don't specify a path, sys.argv[0] reads simply script.py, and os.path.dirname cannot determine a path.




回答2:


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)



回答3:


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.



来源:https://stackoverflow.com/questions/15725273/python-oserror-errno-2-no-such-file-or-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!