简体   繁体   English

以交互方式/非交互方​​式运行时,Python以不同方式导入模块

[英]Python importing modules differently when run interactively/non-interactively

One of my Python scripts runs in interactive mode but fails when run from the command line. 我的一个Python脚本以交互模式运行,但从命令行运行时失败。 The difference is that when run from the command line, it imports modules from a bad .egg file, and when run interactively it uses my fixed (unzipped) version in the current directory. 不同之处在于,当从命令行运行时,它从坏的.egg文件导入模块,并且当以交互方式运行时,它使用当前目录中的固定(解压缩)版本。

My question is two-fold: a) why does Python load modules differently when run from these locations, and b) what are my options to work around it? 我的问题有两个方面:a)为什么Python在从这些位置运行时加载模块的方式不同,以及b)我可以选择解决哪些问题?

On UNIX systems and Mac OS-X: 在UNIX系统和Mac OS-X上:

  • Do you have a ~/.python-eggs directory? 你有一个~/.python-eggs目录吗?

OS independent: OS独立:

  • Are you sure that you use the same Python instance in both cases? 您确定在两种情况下都使用相同的Python实例吗?

  • Can you print sys.path in each cases and see which package directory comes first on your module search path? 你能在每种情况下打印sys.path并查看模块搜索路径中首先出现的软件包目录吗?

I don't understand what do you mean by running script in interactive mode, so I can't say exactly. 我不明白你在交互模式下运行脚本是什么意思,所以我不能完全说出来。 But the first place to look for modules ( sys.path[0] ) in interactive mode is current directory (even calling os.chdir() will affect imports), while for script it's directory where the script is located (derived from sys.argv[0] ). 但是,在交互模式下查找模块( sys.path[0] )的第一个地方是当前目录(甚至调用os.chdir()将影响导入),而对于脚本,它是脚本所在的目录(派生自sys.argv[0] )。 Note that they are effectively the same when script is run from directory where it's located, but could be different in other cases. 请注意,当脚本从其所在的目录运行时,它们实际上是相同的,但在其他情况下可能会有所不同。 Hope this helps. 希望这可以帮助。

a) why does Python load modules differently when run from these locations b) what are my options to work around it? a)为什么Python从这些位置运行时加载模块的方式不同b)我可以选择解决它的哪些方面?

Check your environment variable PYTHONPATH. 检查您的环境变量PYTHONPATH。 When python imports module, it searches those directories. 当python导入模块时,它会搜索这些目录。 One way to get around your problem is to add your local folder "the (unzipped) version in the current directory" to the beginning of PYTHONPATH so that python will find it first. 解决问题的一种方法是将本地文件夹“当前目录中的(解压缩)版本”添加到PYTHONPATH的开头,以便python首先找到它。

This works for me: 这对我有用:

import sys

sys.path[0]=''

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

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