[英]Why does Python fail to run a program when I run it from its own directory?
This is not working: 这不起作用:
numbers is a directory: 数字是目录:
$ cat numbers.py
import networkx as nx
~/numbers $ python2.7 < numbers.py
This gives me a few errors which end with something like: 这给了我一些错误,这些错误的结尾是:
'module' object has no attribute 'Number'
This is working: 这正在工作:
~ $ python2.7 < numbers/numbers.py
I installed networkx following these instructions: http://networkx.github.io/documentation/latest/install.html 我按照以下说明安装了networkx: http ://networkx.github.io/documentation/latest/install.html
Download the source (tar.gz or zip file) from https://pypi.python.org/pypi/networkx/ or get the latest development version from https://github.com/networkx/networkx/
Unpack and change directory to the source directory (it should have the files README.txt and setup.py).
Run python setup.py install to build and install
(Optional) Run nosetests to execute the tests if you have nose installed.
The tests run fine, but I don't understand why the trivial program containing only "import networkx as nx" won't run. 测试运行正常,但是我不明白为什么仅包含“将networkx作为nx导入”的普通程序无法运行。
What is the difference between these two situations ? 这两种情况有什么区别?
You are passing in the script on STDIN, instead of on the command line, so Python adds the current working directory to sys.path
instead of numbers
. 您正在STDIN而不是在命令行上传递脚本,因此Python将当前的工作目录而不是
numbers
添加到sys.path
中。
Normally, Python adds the directory of the script as first element in sys.path
: 通常,Python将脚本目录添加为
sys.path
第一个元素:
As initialized upon program startup, the first item of this list,
path[0]
, is the directory containing the script that was used to invoke the Python interpreter.如程序启动时所初始化,此列表的第一项
path[0]
是包含用于调用Python解释器的脚本的目录。 If the script directory is not available (eg if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first.如果脚本目录不可用(例如,如果交互式调用解释器或从标准输入中读取脚本),则path [0]为空字符串,该字符串将引导Python首先搜索当前目录中的模块。
If you are having import problems, then it sounds as if the wrong module is being imported; 如果您遇到导入问题,那么听起来好像导入了错误的模块; perhaps you are masking a stdlib module with one with the same name, locating in
numbers
. 也许您正在用一个具有相同名称的stdlib模块屏蔽它们,并在
numbers
定位。 Rename that module. 重命名该模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.