繁体   English   中英

从我自己的目录运行Python时,为什么Python无法运行该程序?

[英]Why does Python fail to run a program when I run it from its own directory?

这不起作用:

数字是目录:

$ cat numbers.py
import networkx as nx


~/numbers $ python2.7 < numbers.py

这给了我一些错误,这些错误的结尾是:

'module' object has no attribute 'Number'

这正在工作:

~ $ python2.7 < numbers/numbers.py

我按照以下说明安装了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.

测试运行正常,但是我不明白为什么仅包含“将networkx作为nx导入”的普通程序无法运行。

这两种情况有什么区别?

您正在STDIN而不是在命令行上传递脚本,因此Python将当前的工作目录而不是numbers添加到sys.path中。

通常,Python将脚本目录添加为sys.path第一个元素:

如程序启动时所初始化,此列表的第一项path[0]是包含用于调用Python解释器的脚本的目录。 如果脚本目录不可用(例如,如果交互式调用解释器或从标准输入中读取脚本),则path [0]为空字符串,该字符串将引导Python首先搜索当前目录中的模块。

如果您遇到导入问题,那么听起来好像导入了错误的模块; 也许您正在用一个具有相同名称的stdlib模块屏蔽它们,并在numbers定位。 重命名该模块。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM