22

我有一个 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!)

运行时,

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

我收到错误:

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: ''

我应该如何阅读此错误以及该怎么做?

4

4 回答 4

35

你有没有注意到如果你运行你没有得到错误

python ./script.py

代替

python script.py

这是因为sys.argv[0]./script.py在前一种情况下阅读,这提供了os.path.dirname一些可以使用的东西。当您不指定路径时,sys.argv[0]读取简单script.py,并且os.path.dirname无法确定路径。

于 2013-03-31T01:19:02.723 回答
30

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)
于 2015-04-21T14:26:58.523 回答
20

使用os.path.abspath()

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

sys.argv[0]在您的情况下只是一个脚本名称,没有目录,因此os.path.dirname()返回一个空字符串。

os.path.abspath()将其转换为具有目录名称的正确绝对路径。

于 2013-03-31T01:17:34.977 回答
-1

I was compiling the android code v4.4 on Ubuntu 14.04, when I met the same problem of Python, no such file or directory.

It ends as I installed below libraries. So I think maybe it will help someone at some occasion. The python script takes it for granted that some lib exists in the system.

sudo apt install gperf
sudo apt install  libxml2-utils
sudo apt install libbison-dev

于 2021-04-18T07:45:50.827 回答