Python:OSError:[Errno 2] 没有那个文件或目录:''
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15725273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: OSError: [Errno 2] No such file or directory: ''
提问by Hugolpz
I have a 100 lines, 3 years old python scraper that now bug. Starting lines are:
我有一个 100 行、3 岁的 python 刮板,现在是错误的。起跑线是:
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 ?
我应该如何阅读此错误以及该怎么做?
采纳答案by zigg
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.pyin the former case, which gives os.path.dirnamesomething to work with. When you don't specify a path, sys.argv[0]reads simply script.py, and os.path.dirnamecannot determine a path.
这是因为sys.argv[0]will read./script.py在前一种情况下,它提供了os.path.dirname一些可以使用的东西。不指定路径时,只sys.argv[0]读取script.py,os.path.dirname无法确定路径。
回答by Martijn Pieters
Use os.path.abspath():
使用os.path.abspath():
os.chdir(os.path.dirname(os.path.abspath(sys.argv[0])))
sys.argv[0]in your case is justa script name, no directory, so os.path.dirname()returns an empty string.
sys.argv[0]在你的情况下只是一个脚本名称,没有目录,所以os.path.dirname()返回一个空字符串。
os.path.abspath()turns that into a proper absolute path with directory name.
os.path.abspath()将其转换为带有目录名称的正确绝对路径。
回答by Moebius
I had this error because I was providing a string of arguments to subprocess.callinstead of an array of arguments. To prevent this, use shlex.split:
我有这个错误,因为我提供了一个参数字符串subprocess.call而不是一个参数数组。为了防止这种情况,请使用shlex.split:
import shlex, subprocess
command_line = "ls -a"
args = shlex.split(command_line)
p = subprocess.Popen(args)

![Python `Sudo pip install matplotlib` 无法找到 freetype 标头。[OS X 小牛队 / 10.9]](/res/img/loading.gif)