标签归档:python-import

为什么在导入模块时Python运行我的模块,以及如何停止它?

问题:为什么在导入模块时Python运行我的模块,以及如何停止它?

我有一个正在构建的Python程序,可以通过以下两种方式之一运行:第一种是调用“ python main.py”,它以友好的方式提示用户输入,然后通过该程序运行用户输入。另一种方法是调用“ python batch.py -file- ”,它将遍历所有友好的输入集合,并通过该程序一次运行整个文件的输入值。

问题是,当我运行“ batch.py​​”时,它会从“ main.py”中导入一些变量/方法/等,并在运行此代码时:

import main

在程序的第一行,它立即错误,因为它试图运行“ main.py”中的代码。

如何阻止Python运行要导入的“主”模块中包含的代码?

I have a Python program I’m building that can be run in either of 2 ways: the first is to call “python main.py” which prompts the user for input in a friendly manner and then runs the user input through the program. The other way is to call “python batch.py -file-” which will pass over all the friendly input gathering and run an entire file’s worth of input through the program in a single go.

The problem is that when I run “batch.py” it imports some variables/methods/etc from “main.py”, and when it runs this code:

import main

at the first line of the program, it immediately errors because it tries to run the code in “main.py”.

How can I stop Python from running the code contained in the “main” module which I’m importing?


回答 0

因为这就是Python的工作方式,诸如classand之def类的关键字不是声明。相反,它们是执行的真实实时语句。如果未执行,则您的模块将为..空:-)

无论如何,惯用的方法是:

# stuff to run always here such as class/def
def main():
    pass

if __name__ == "__main__":
   # stuff only to run when not called via 'import' here
   main()

请参阅目的是什么if __name__ == "__main__"

但是,它确实需要对要import编辑的模块进行源代码控制。

快乐的编码。

Because this is just how Python works – keywords such as class and def are not declarations. Instead, they are real live statements which are executed. If they were not executed your module would be .. empty :-)

Anyway, the idiomatic approach is:

# stuff to run always here such as class/def
def main():
    pass

if __name__ == "__main__":
   # stuff only to run when not called via 'import' here
   main()

See What is if __name__ == "__main__" for?

It does require source control over the module being imported, however.

Happy coding.


回答 1

由于Python的工作方式,在导入模块时必须运行模块。

为了防止模块中的代码在导入时被执行,而只能在直接运行时执行,可以使用以下方法进行保护if

if __name__ == "__main__":
    # this won't be run when imported

您可能需要将此代码放入main()方法中,以便可以直接执行文件,或导入模块并调用main()。例如,假设它在file中foo.py

def main():
    print "Hello World"

if __name__ == "__main__":
    main()

该程序可以通过运行python foo.py或从另一个Python脚本运行:

import foo

...

foo.main()

Due to the way Python works, it is necessary for it to run your modules when it imports them.

To prevent code in the module from being executed when imported, but only when run directly, you can guard it with this if:

if __name__ == "__main__":
    # this won't be run when imported

You may want to put this code in a main() method, so that you can either execute the file directly, or import the module and call the main(). For example, assume this is in the file foo.py.

def main():
    print "Hello World"

if __name__ == "__main__":
    main()

This program can be run either by going python foo.py, or from another Python script:

import foo

...

foo.main()

回答 2

使用if __name__ == '__main__'惯用语- __name__是一个特殊变量,其值是'__main__'模块是否作为脚本运行时的值,模块名称(如果已导入)。所以你会做类似的事情

# imports
# class/function definitions
if __name__ == '__main__':
    # code here will only run when you invoke 'python main.py'

Use the if __name__ == '__main__' idiom — __name__ is a special variable whose value is '__main__' if the module is being run as a script, and the module name if it’s imported. So you’d do something like

# imports
# class/function definitions
if __name__ == '__main__':
    # code here will only run when you invoke 'python main.py'

回答 3

不幸的是,您没有。这是导入语法工作方式的一部分,并且重要的是,请记住这一点-记住def实际上是已执行某项操作,如果Python不执行导入,那么您将被困在没有函数的情况下。

但是,由于您可能可以访问该文件,因此您可以查看并查看导致该错误的原因。可能有可能修改您的环境以防止发生错误。

Unfortunately, you don’t. That is part of how the import syntax works and it is important that it does so — remember def is actually something executed, if Python did not execute the import, you’d be, well, stuck without functions.

Since you probably have access to the file, though, you might be able to look and see what causes the error. It might be possible to modify your environment to prevent the error from happening.


回答 4

将代码放入函数中,直到调用该函数,该代码才会运行。您应该在其中具有主要功能main.py。带有以下语句:

if __name__ == '__main__':
  main()

然后,如果调用python main.pymain()函数将运行。如果导入main.py,则不会。另外,main.py为清楚起见,您可能应该重命名为其他名称。

Put the code inside a function and it won’t run until you call the function. You should have a main function in your main.py. with the statement:

if __name__ == '__main__':
  main()

Then, if you call python main.py the main() function will run. If you import main.py, it will not. Also, you should probably rename main.py to something else for clarity’s sake.


回答 5

有一个Python增强建议PEP 299,旨在用替换if __name__ == '__main__':成语def __main__:,但遭到拒绝。了解使用时要记住的内容仍然是一本好书if __name__ = '__main__':

There was a Python enhancement proposal PEP 299 which aimed to replace if __name__ == '__main__': idiom with def __main__:, but it was rejected. It’s still a good read to know what to keep in mind when using if __name__ = '__main__':.


回答 6

您可以这样编写“ main.py”:

#!/usr/bin/env python

__all__=["somevar", "do_something"]

somevar=""

def do_something():
    pass #blahblah

if __name__=="__main__":
    do_something()

You may write your “main.py” like this:

#!/usr/bin/env python

__all__=["somevar", "do_something"]

somevar=""

def do_something():
    pass #blahblah

if __name__=="__main__":
    do_something()

回答 7

尽管import不运行代码就无法使用;您可以通过很快速的方式输入变量;通过使用numpy.savez,将变量作为numpy数组存储在.npz文件中。之后,您可以使用加载变量numpy.load

查看scipy文档中的完整描述

请注意,这仅适用于变量和变量数组,而不适用于方法等。

Although you cannot use import without running the code; there is quite a swift way in which you can input your variables; by using numpy.savez, which stores variables as numpy arrays in a .npz file. Afterwards you can load the variables using numpy.load.

See a full description in the scipy documentation

Please note this is only the case for variables and arrays of variable, and not for methods, etc.


回答 8

尝试仅从main.py导入所需的功能?所以,

from main import SomeFunction

可能是因为您在batch.py​​中命名的函数与main.py中的命名相同,并且在导入main.py时,程序将运行main.py函数而不是batch.py​​函数;执行以上操作可以解决该问题。我希望。

Try just importing the functions needed from main.py? So,

from main import SomeFunction

It could be that you’ve named a function in batch.py the same as one in main.py, and when you import main.py the program runs the main.py function instead of the batch.py function; doing the above should fix that. I hope.


为什么从__future__ import print_function使用会破坏Python2样式的打印?[关闭]

问题:为什么从__future__ import print_function使用会破坏Python2样式的打印?[关闭]

我是使用python编程的新手,但我尝试使用分隔符并结束打印,但这仍然给我带来语法错误。

我正在使用python 2.7。

这是我的代码:

from __future__ import print_function
import sys, os, time

for x in range(0,10):
    print x, sep=' ', end=''
    time.sleep(1)

这是错误:

$ python2 xy.py
  File "xy.py", line 5
    print x, sep=' ', end=''
          ^
SyntaxError: invalid syntax
$

I am new at programming with python, and I am trying to print out with a separator and end but it is still giving me a syntax error.

I am using python 2.7.

Here is my code:

from __future__ import print_function
import sys, os, time

for x in range(0,10):
    print x, sep=' ', end=''
    time.sleep(1)

And here is the error:

$ python2 xy.py
  File "xy.py", line 5
    print x, sep=' ', end=''
          ^
SyntaxError: invalid syntax
$

回答 0

首先,from __future__ import print_function必须是脚本中的第一行代码(除了下面提到的一些exceptions)。第二,正如其他答案所说,您现在必须print用作函数。这就是重点from __future__ import print_function;将print 功能从Python 3带入Python 2.6+。

from __future__ import print_function

import sys, os, time

for x in range(0,10):
    print(x, sep=' ', end='')  # No need for sep here, but okay :)
    time.sleep(1)

__future__语句必须位于文件的顶部,因为它们会更改语言的基本内容,因此编译器需要从一开始就了解它们。从文档中

将来的语句在编译时会得到特殊识别和处理:更改核心结构的语义通常是通过生成不同的代码来实现的。甚至可能是新功能引入了新的不兼容语法(例如新的保留字)的情况,在这种情况下,编译器可能需要以不同的方式解析模块。直到运行时才能推迟此类决策。

该文档还提到,__future__语句之前唯一可以做的事情就是模块文档字符串,注释,空白行和其他将来的语句。

First of all, from __future__ import print_function needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print as a function now. That’s the whole point of from __future__ import print_function; to bring the print function from Python 3 into Python 2.6+.

from __future__ import print_function

import sys, os, time

for x in range(0,10):
    print(x, sep=' ', end='')  # No need for sep here, but okay :)
    time.sleep(1)

__future__ statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

The documentation also mentions that the only things that can precede a __future__ statement are the module docstring, comments, blank lines, and other future statements.


没有名为_sqlite3的模块

问题:没有名为_sqlite3的模块

我试图在运行Debian 5的VPS上运行Django应用程序。运行演示应用程序时,它返回此错误:

  File "/usr/local/lib/python2.5/site-packages/django/utils/importlib.py", line 35, in     import_module
    __import__(name)

  File "/usr/local/lib/python2.5/site-packages/django/db/backends/sqlite3/base.py", line 30, in <module>
    raise ImproperlyConfigured, "Error loading %s: %s" % (module, exc)

ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that     order): No module named _sqlite3

查看Python安装,它给出了相同的错误:

Python 2.5.2 (r252:60911, May 12 2009, 07:46:31) 
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.5/sqlite3/__init__.py", line 24, in <module>
    from dbapi2 import *
  File "/usr/local/lib/python2.5/sqlite3/dbapi2.py", line 27, in <module>
    from _sqlite3 import *
ImportError: No module named _sqlite3
>>>

在网上阅读后,我了解到Python 2.5应该附带所有必需的SQLite包装器。我需要重新安装Python,还是有另一种方法来启动和运行此模块?

I am trying to run a Django app on my VPS running Debian 5. When I run a demo app, it comes back with this error:

  File "/usr/local/lib/python2.5/site-packages/django/utils/importlib.py", line 35, in     import_module
    __import__(name)

  File "/usr/local/lib/python2.5/site-packages/django/db/backends/sqlite3/base.py", line 30, in <module>
    raise ImproperlyConfigured, "Error loading %s: %s" % (module, exc)

ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that     order): No module named _sqlite3

Looking at the Python install, it gives the same error:

Python 2.5.2 (r252:60911, May 12 2009, 07:46:31) 
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.5/sqlite3/__init__.py", line 24, in <module>
    from dbapi2 import *
  File "/usr/local/lib/python2.5/sqlite3/dbapi2.py", line 27, in <module>
    from _sqlite3 import *
ImportError: No module named _sqlite3
>>>

Reading on the web, I learn that Python 2.5 should come with all the necessary SQLite wrappers included. Do I need to reinstall Python, or is there another way to get this module up and running?


回答 0

您的makefile文件似乎没有包含适当的.so文件。您可以按照以下步骤纠正此问题:

  1. 安装sqlite-devel(或libsqlite3-dev在某些基于Debian的系统上)
  2. 使用以下命令重新配置和重新编译Python ./configure --enable-loadable-sqlite-extensions && make && sudo make install

注意

sudo make install部分将把python版本设置为系统范围的标准,这可能会产生无法预料的后果。如果您在工作站上运行此命令,则可能希望将其现有python 一起安装,可以使用来完成sudo make altinstall

It seems your makefile didn’t include the appropriate .so file. You can correct this problem with the steps below:

  1. Install sqlite-devel (or libsqlite3-dev on some Debian-based systems)
  2. Re-configure and re-compiled Python with ./configure --enable-loadable-sqlite-extensions && make && sudo make install

Note

The sudo make install part will set that python version to be the system-wide standard, which can have unforseen consequences. If you run this command on your workstation, you’ll probably want to have it installed alongside the existing python, which can be done with sudo make altinstall.


回答 1

我遇到了同样的问题(python2.5从Ubuntu Lucid上的源代码构建),并import sqlite3抛出了同样的异常。我已经libsqlite3-dev从软件包管理器安装了,重新编译了python2.5,然后导入工作了。

I had the same problem (building python2.5 from source on Ubuntu Lucid), and import sqlite3 threw this same exception. I’ve installed libsqlite3-dev from the package manager, recompiled python2.5, and then the import worked.


回答 2

使用pyenv时,我在Ubuntu上的Python 3.5遇到了相同的问题。

如果您使用pyenv安装python ,则将其列为常见的构建问题之一。要解决此问题,请删除已安装的python版本,安装要求(针对此特殊情况libsqlite3-dev),然后重新安装python版本。

I had the same problem with Python 3.5 on Ubuntu while using pyenv.

If you’re installing the python using pyenv, it’s listed as one of the common build problems. To solve it, remove the installed python version, install the requirements (for this particular case libsqlite3-dev), then reinstall the python version.


回答 3

这就是我为使其正常工作所做的。

我正在使用安装了python 2.7.5的pythonbrew(正在使用pip)。

我首先执行了Zubair(上面)所说的,然后运行了以下命令:

sudo apt-get install libsqlite3-dev

然后我运行以下命令:

pip install pysqlite

这解决了数据库问题,我在运行时得到了确认:

python manager.py syncdb

This is what I did to get it to work.

I am using pythonbrew(which is using pip) with python 2.7.5 installed.

I first did what Zubair(above) said and ran this command:

sudo apt-get install libsqlite3-dev

Then I ran this command:

pip install pysqlite

This fixed the database problem and I got confirmation of this when I ran:

python manager.py syncdb

回答 4

  1. 安装sqlite-devel软件包:

    yum install sqlite-devel -y

  2. 从源代码重新编译python:

    ./configure
    make
    make altinstall
  1. Install the sqlite-devel package:

    yum install sqlite-devel -y

  2. Recompile python from the source:

    ./configure
    make
    make altinstall
    

回答 5

我的_sqlite3.so位于/usr/lib/python2.5/lib-dynload/_sqlite3.so中。从您的路径来看,您应该拥有文件/usr/local/lib/python2.5/lib-dynload/_sqlite3.so。

尝试以下方法:

find /usr/local -name _sqlite3.so

如果找不到该文件,则说明您的Python安装可能有问题。如果是,请确保其安装路径在Python路径中。在Python Shell中,

import sys
print sys.path

就我而言,/usr/lib/python2.5/lib-dynload在列表中,因此它可以找到/usr/lib/python2.5/lib-dynload/_sqlite3.so。

My _sqlite3.so is in /usr/lib/python2.5/lib-dynload/_sqlite3.so. Judging from your paths, you should have the file /usr/local/lib/python2.5/lib-dynload/_sqlite3.so.

Try the following:

find /usr/local -name _sqlite3.so

If the file isn’t found, something may be wrong with your Python installation. If it is, make sure the path it’s installed to is in the Python path. In the Python shell,

import sys
print sys.path

In my case, /usr/lib/python2.5/lib-dynload is in the list, so it’s able to find /usr/lib/python2.5/lib-dynload/_sqlite3.so.


回答 6

我最近尝试在Ubuntu 11.04桌面上安装python 2.6.7,以进行一些开发工作。遇到了与此线程类似的问题。我想通过以下方式修复它:

  1. 调整setup.py文件以包含正确的sqlite开发路径。setup.py中的代码片段:

    def sqlite_incdir:
    sqlite_dirs_to_check = [
    os.path.join(sqlite_incdir, '..', 'lib64'),
    os.path.join(sqlite_incdir, '..', 'lib'),
    os.path.join(sqlite_incdir, '..', '..', 'lib64'),
    os.path.join(sqlite_incdir, '..', '..', 'lib'),
    '/usr/lib/x86_64-linux-gnu/'
    ]

    我添加的位是’/ usr / lib / x86_64-linux-gnu /’。

  2. 运行make之后,我没有收到任何警告,提示未构建sqlite支持(即,它正确构建了:P),但是运行后make install,sqlite3仍未使用相同的“ ImportError: No module named _sqlite3" whe running "import sqlite3” 导入。

    因此,该库已编译,但未移至正确的安装路径,因此我复制了该.so文件(cp /usr/src/python/Python-2.6.7/build/lib.linux-x86_64-2.6/_sqlite3.so /usr/local/python-2.6.7/lib/python2.6/sqlite3/这些是我的构建路径,您可能需要根据设置进行调整)。

瞧!现在支持SQLite3。

I recently tried installing python 2.6.7 on my Ubuntu 11.04 desktop for some dev work. Came across similar problems to this thread. I mamaged to fix it by:

  1. Adjusting the setup.py file to include the correct sqlite dev path. Code snippet from setup.py:

    def sqlite_incdir:
    sqlite_dirs_to_check = [
    os.path.join(sqlite_incdir, '..', 'lib64'),
    os.path.join(sqlite_incdir, '..', 'lib'),
    os.path.join(sqlite_incdir, '..', '..', 'lib64'),
    os.path.join(sqlite_incdir, '..', '..', 'lib'),
    '/usr/lib/x86_64-linux-gnu/'
    ]
    

    With the bit that I added being ‘/usr/lib/x86_64-linux-gnu/’.

  2. After running make I did not get any warnings saying the sqlite support was not built (i.e., it built correctly :P ), but after running make install, sqlite3 still did not import with the same “ImportError: No module named _sqlite3" whe running "import sqlite3“.

    So, the library was compiled, but not moved to the correct installation path, so I copied the .so file (cp /usr/src/python/Python-2.6.7/build/lib.linux-x86_64-2.6/_sqlite3.so /usr/local/python-2.6.7/lib/python2.6/sqlite3/ — these are my build paths, you will probably need to adjust them to your setup).

Voila! SQLite3 support now works.


回答 7

我发现很多人都遇到了这个问题,因为在我自己的vps(cent os 7 x64)上,Multi-version Python是通过以下方式解决的:

  1. 找到文件“ _sqlite3.so”

    find / -name _sqlite3.so

    出: /usr/lib64/python2.7/lib-dynload/_sqlite3.so

  2. 找到您要使用的python标准库的目录,

    为了我 /usr/local/lib/python3.6/lib-dynload

  3. 复制文件:

    cp   /usr/lib64/python2.7/lib-dynload/_sqlite3.so /usr/local/lib/python3.6/lib-dynload

最后,一切都会好的。

I found lots of people meet this problem because the Multi-version Python, on my own vps (cent os 7 x64), I solved it in this way:

  1. Find the file “_sqlite3.so”

    find / -name _sqlite3.so
    

    out: /usr/lib64/python2.7/lib-dynload/_sqlite3.so

  2. Find the dir of python Standard library you want to use,

    for me /usr/local/lib/python3.6/lib-dynload

  3. Copy the file:

    cp   /usr/lib64/python2.7/lib-dynload/_sqlite3.so /usr/local/lib/python3.6/lib-dynload
    

Finally, everything will be ok.


回答 8

这在Redhat Centos 6.5中对我有用:

yum install sqlite-devel
pip install pysqlite

This worked for me in Redhat Centos 6.5:

yum install sqlite-devel
pip install pysqlite

回答 9

我的python是从源代码构建的,原因是在exec配置python版本时缺少选项:3.7.4

./configure --enable-loadable-sqlite-extensions --enable-optimizations
make
make install

固定

my python is build from source, the cause is missing options when exec configure python version:3.7.4

./configure --enable-loadable-sqlite-extensions --enable-optimizations
make
make install

fixed


回答 10

我在FreeBSD 8.1中有问题:

- No module named _sqlite3 -

通过站立端口解决———-

/usr/ports/databases/py-sqlite3

在此之后可以看到:

OK ----------
'>>>' import sqlite3 -----
'>>>' sqlite3.apilevel -----
'2.0'

I have the problem in FreeBSD 8.1:

- No module named _sqlite3 -

It is solved by stand the port ———-

/usr/ports/databases/py-sqlite3

after this one can see:

OK ----------
'>>>' import sqlite3 -----
'>>>' sqlite3.apilevel -----
'2.0'

回答 11

是否安装了python-pysqlite2软件包?

sudo apt-get install python-pysqlite2

Is the python-pysqlite2 package installed?

sudo apt-get install python-pysqlite2

回答 12

检查您的settings.py文件。您是否不仅为数据库引擎编写了“ sqlite”而不是“ sqlite3”?

Checking your settings.py file. Did you not just write “sqlite” instead of “sqlite3” for the database engine?


回答 13

sqlite3Python附带。我也有同样的问题,我只是卸载python3.6并重新安装了它。

卸载现有的python:

sudo apt-get remove --purge python3.6

安装python3.6:

sudo apt install build-essential checkinstall
sudo apt install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev
wget https://www.python.org/ftp/python/3.6.0/Python-3.6.0.tar.xz
tar xvf Python-3.6.0.tar.xz
cd Python-3.6.0/
./configure
sudo make altinstall

sqlite3 ships with Python. I also had the same problem, I just uninstalled python3.6 and installed it again.

Uninstall existing python:

sudo apt-get remove --purge python3.6

Install python3.6:

sudo apt install build-essential checkinstall
sudo apt install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev
wget https://www.python.org/ftp/python/3.6.0/Python-3.6.0.tar.xz
tar xvf Python-3.6.0.tar.xz
cd Python-3.6.0/
./configure
sudo make altinstall

回答 14

您必须使用centos或redhat并自己编译python,这是python的错误,请在python源代码目录中执行此操作,并在下面执行此操作

curl -sk https://gist.github.com/msabramo/2727063/raw/59ea097a1f4c6f114c32f7743308a061698b17fd/gistfile1.diff | patch -p1

you must be in centos or redhat and compile python yourself, it is python‘s bug do this in your python source code dir and do this below

curl -sk https://gist.github.com/msabramo/2727063/raw/59ea097a1f4c6f114c32f7743308a061698b17fd/gistfile1.diff | patch -p1

回答 15

我遇到了同样的问题,上述问题对我没有任何帮助,但是现在我通过

只是删除python.pipsqlite3并重新安装

  1. sudo apt-get remove python.pip
  2. sudo apt-get remove sqlite3

现在再次安装

  1. sudo apt-get install python.pip
  2. sudo apt-get install sqlite3

在我的情况下sqlite3再次安装时它显示了一些错误,然后我键入

  1. sqlite3

在终端上检查是否已卸下,然后开始拆箱

一旦sqlite3安装了启动终端并写入

  1. sqlite3
  2. database.db (创建数据库)

我相信这一定会对您有帮助

I got the same problem, nothing worked for me from the above ans but now I fixed it by

just remove python.pip and sqlite3 and reinstall

  1. sudo apt-get remove python.pip
  2. sudo apt-get remove sqlite3

now install it again

  1. sudo apt-get install python.pip
  2. sudo apt-get install sqlite3

in my case while installing sqlite3 again it showed some error then I typed

  1. sqlite3

on terminal to check if it was removed or not and it started unpacking it

once the sqlite3 is installed fireup terminal and write

  1. sqlite3
  2. database.db (to create a database)

I’m sure this will definitely help you


回答 16

为登录此页面的任何人提供答案,以寻找适用于Windows OS的解决方案:

如果尚未安装pysqlite3或db-sqlite3,则必须安装。您可以使用以下安装。

  • pip安装pysqlite3
  • pip安装db-sqlite3

对我来说,问题在于sqlite3的DLL文件。

解:

  1. 我从sqlite网站上获取了DLL文件。这可能会因您安装的python版本而异。

  2. 我将其粘贴到env的DLL目录中。对我来说,它是“ C:\ Anaconda \ Lib \ DLLs”,但请检查您的。 放置DLL文件前后

Putting answer for anyone who lands on this page searching for a solution for Windows OS:

You have to install pysqlite3 or db-sqlite3 if not already installed. you can use following to install.

  • pip install pysqlite3
  • pip install db-sqlite3

For me the issue was with DLL file of sqlite3.

Solution:

  1. I took DLL file from sqlite site. This might vary based on your version of python installation.

  2. I pasted it in the DLL directory of the env. for me it was “C:\Anaconda\Lib\DLLs”, but check for yours. Before and After placing DLL file


回答 17

令我感到失望的是,这个问题一直存在到今天。由于我最近一直在尝试在CentOS 8.1上安装vCD CLI,因此在尝试运行它时出现相同的错误,对此我表示欢迎。在我的情况下,我必须解决的方法如下:

  • 使用适当的前缀从头开始安装SQLite3
  • 清理我的Python安装
  • 运行Make install重新安装Python

正如我一直在做的那样,以创建有关如何安装vCD CLI和VMware Container Service Extension的不同博客文章。我最终捕获了用于解决此问题的步骤,并将其放在单独的博客文章中,网址为:

http://www.virtualizationteam.com/cloud/running-vcd-cli-fail-with-the-following-error-modulenotfounderror-no-module-named-_sqlite3.html

我希望这会有所帮助,因为尽管上面的提示帮助我找到了解决方案,但我不得不将其中的几个结合起来并进行一些修改。

I was disappointed this issue still exist till today. As I have recently been trying to install vCD CLI on CentOS 8.1 and I was welcomed with the same error when tried to run it. The way I had to resolve it in my case is as follow:

  • Install SQLite3 from scratch with the proper prefix
  • Make clean my Python Installation
  • Run Make install to reinstall Python

As I have been doing this to create a different blogpost about how to install vCD CLI and VMware Container Service Extension. I have end up capturing the steps I used to fix the issue and put it in a separate blog post at:

http://www.virtualizationteam.com/cloud/running-vcd-cli-fail-with-the-following-error-modulenotfounderror-no-module-named-_sqlite3.html

I hope this helpful, as while the tips above had helped me get to a solution, I had to combine few of them and modify them a bit.


回答 18

下载sqlite3:

wget http://www.sqlite.org/2016/sqlite-autoconf-3150000.tar.gz

请按照以下步骤进行安装:

$tar xvfz sqlite-autoconf-3071502.tar.gz
$cd sqlite-autoconf-3071502
$./configure --prefix=/usr/local
$make install

Download sqlite3:

wget http://www.sqlite.org/2016/sqlite-autoconf-3150000.tar.gz

Follow these steps to install:

$tar xvfz sqlite-autoconf-3071502.tar.gz
$cd sqlite-autoconf-3071502
$./configure --prefix=/usr/local
$make install

回答 19

您需要在python环境中安装pysqlite

    $ pip install pysqlite

You need to install pysqlite in your python environment:

    $ pip install pysqlite

回答 20

尝试复制 _sqlite3.so以便Python可以找到它。

它应该很简单:

cp /usr/lib64/python2.6/lib-dynload/_sqlite3.so /usr/local/lib/python2.7/

相信我,尝试一下。

Try copying _sqlite3.so so that Python can find it.

It should be as simple as:

cp /usr/lib64/python2.6/lib-dynload/_sqlite3.so /usr/local/lib/python2.7/

Trust me, try it.


将目录添加到sys.path / PYTHONPATH

问题:将目录添加到sys.path / PYTHONPATH

我正在尝试从特定目录导入模块。

问题是,如果我使用sys.path.append(mod_directory)追加路径然后打开python解释器,该目录mod_directory将添加到列表sys.path的末尾。如果我PYTHONPATH在打开python解释器之前导出变量,则目录将添加到列表的开头。在后一种情况下,我可以导入模块,但是在前一种情况下,我不能。

有人可以解释为什么会发生这种情况,并给我一个 python脚本中将其添加mod_directory到开始的解决方案吗?

I am trying to import a module from a particular directory.

The problem is that if I use sys.path.append(mod_directory) to append the path and then open the python interpreter, the directory mod_directory gets added to the end of the list sys.path. If I export the PYTHONPATH variable before opening the python interpreter, the directory gets added to the start of the list. In the latter case I can import the module but in the former, I cannot.

Can somebody explain why this is happening and give me a solution to add the mod_directory to the start, inside a python script ?


回答 0

如文档所述,这正在工作。PYTHONPATH文件中指定的所有路径通常在工作目录之后但在标准解释器提供的路径之前记录。 sys.path.append()追加到现有路径。看到这里这里。如果要让特定目录优先出现,只需将其插入sys.path的开头即可:

import sys
sys.path.insert(0,'/path/to/mod_directory')

就是说,通常有比直接使用PYTHONPATH或操纵更好的方法来管理进口sys.path。例如,请参阅此问题的答案。

This is working as documented. Any paths specified in PYTHONPATH are documented as normally coming after the working directory but before the standard interpreter-supplied paths. sys.path.append() appends to the existing path. See here and here. If you want a particular directory to come first, simply insert it at the head of sys.path:

import sys
sys.path.insert(0,'/path/to/mod_directory')

That said, there are usually better ways to manage imports than either using PYTHONPATH or manipulating sys.path directly. See, for example, the answers to this question.


回答 1

您可以使用:

import os
path = 'the path you want'
os.environ['PATH'] += ':'+path

You could use:

import os
path = 'the path you want'
os.environ['PATH'] += ':'+path

回答 2

对于我来说,我需要了解我的python路径。我可以将它的路径添加到该文件 /home/xy/.bashrc由add

export PYTHONPATH=/home/xy/caffe-master/python:$PYTHONPATH

到我的/home/xy/.bashrc文件。

但是当我使用pycharm时,路径仍然不在。

因此,我可以PYTHONPATH通过运行->编辑配置将路径添加到变量。

在此处输入图片说明

As to me, i need to caffe to my python path. I can add it’s path to the file /home/xy/.bashrc by add

export PYTHONPATH=/home/xy/caffe-master/python:$PYTHONPATH.

to my /home/xy/.bashrc file.

But when I use pycharm, the path is still not in.

So I can add path to PYTHONPATH variable, by run -> edit Configuration.

enter image description here


回答 3

临时更改目录可以很好地导入:

cwd = os.getcwd()
os.chdir(<module_path>)
import <module>
os.chdir(cwd)

Temporarily changing dirs works well for importing:

cwd = os.getcwd()
os.chdir(<module_path>)
import <module>
os.chdir(cwd)

回答 4

在Windows下从Powershell运行Python脚本时,这应该可以工作:

$pathToSourceRoot = "C:/Users/Steve/YourCode"
$env:PYTHONPATH = "$($pathToSourceRoot);$($pathToSourceRoot)/subdirs_if_required"

# Now run the actual script
python your_script.py

When running a Python script from Powershell under Windows, this should work:

$pathToSourceRoot = "C:/Users/Steve/YourCode"
$env:PYTHONPATH = "$($pathToSourceRoot);$($pathToSourceRoot)/subdirs_if_required"

# Now run the actual script
python your_script.py

Python鼻子导入错误

问题:Python鼻子导入错误

我似乎无法获得鼻子测试框架来识别文件结构中测试脚本下的模块。我设置了最简单的示例来演示该问题。我会在下面解释。

这是包文件的结构:

./__init__.py
./foo.py
./tests
   ./__init__.py
   ./test_foo.py

foo.py包含:

def dumb_true():
    return True

tests / test_foo.py包含:

import foo

def test_foo():
    assert foo.dumb_true()

两个init .py文件均为空

如果我nosetests -vv在主目录(foo.py所在的目录)中运行,则会得到:

Failure: ImportError (No module named foo) ... ERROR

======================================================================
ERROR: Failure: ImportError (No module named foo)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib/python/site-packages/nose-0.11.1-py2.6.egg/nose/loader.py", line 379, in loadTestsFromName
    addr.filename, addr.module)
  File "/usr/lib/python/site-packages/nose-0.11.1-py2.6.egg/nose/importer.py", line 39, in importFromPath
    return self.importFromDir(dir_path, fqname)
  File "/usr/lib/python/site-packages/nose-0.11.1-py2.6.egg/nose/importer.py", line 86, in importFromDir
    mod = load_module(part_fqname, fh, filename, desc)
  File "/home/user/nose_testing/tests/test_foo.py", line 1, in <module>
    import foo
ImportError: No module named foo

----------------------------------------------------------------------
Ran 1 test in 0.002s

FAILED (errors=1)

当我从tests /目录中运行时,出现相同的错误。根据文档和我发现的示例,nose应该将所有父包都添加到路径以及调用它的目录中,但是在我看来,这似乎没有发生。

我正在使用Python 2.6.2运行Ubuntu 8.04。如果重要的话,我已经手动构建并安装了鼻子(不使用setup_tools)。

I can’t seem to get the nose testing framework to recognize modules beneath my test script in the file structure. I’ve set up the simplest example that demonstrates the problem. I’ll explain it below.

Here’s the the package file structure:

./__init__.py
./foo.py
./tests
   ./__init__.py
   ./test_foo.py

foo.py contains:

def dumb_true():
    return True

tests/test_foo.py contains:

import foo

def test_foo():
    assert foo.dumb_true()

Both init.py files are empty

If I run nosetests -vv in the main directory (where foo.py is), I get:

Failure: ImportError (No module named foo) ... ERROR

======================================================================
ERROR: Failure: ImportError (No module named foo)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib/python/site-packages/nose-0.11.1-py2.6.egg/nose/loader.py", line 379, in loadTestsFromName
    addr.filename, addr.module)
  File "/usr/lib/python/site-packages/nose-0.11.1-py2.6.egg/nose/importer.py", line 39, in importFromPath
    return self.importFromDir(dir_path, fqname)
  File "/usr/lib/python/site-packages/nose-0.11.1-py2.6.egg/nose/importer.py", line 86, in importFromDir
    mod = load_module(part_fqname, fh, filename, desc)
  File "/home/user/nose_testing/tests/test_foo.py", line 1, in <module>
    import foo
ImportError: No module named foo

----------------------------------------------------------------------
Ran 1 test in 0.002s

FAILED (errors=1)

I get the same error when I run from inside the tests/ directory. According to the documentation and an example I found, nose is supposed to add all parent packages to the path as well as the directory from which it is called, but this doesn’t seem to be happening in my case.

I’m running Ubuntu 8.04 with Python 2.6.2. I’ve built and installed nose manually (not with setup_tools) if that matters.


回答 0

__init__.py的顶级目录中有一个。这使其成为一个包装。如果将其删除,则nosetests应该可以工作。

如果不删除它,则必须将其更改importimport dir.foo,这dir是目录名。

You’ve got an __init__.py in your top level directory. That makes it a package. If you remove it, your nosetests should work.

If you don’t remove it, you’ll have to change your import to import dir.foo, where dir is the name of your directory.


回答 1

您在虚拟环境中吗?就我而言,nosetests是中的/usr/bin/nosetests,正在使用/usr/bin/python。virtualenv中的软件包肯定不会在系统路径中。以下解决了此问题:

source myvirtualenv/activate
pip install nose
which nosetests
/home/me/myvirtualenv/bin/nosetests

Are you in a virtualenv? In my case, nosetests was the one in /usr/bin/nosetests, which was using /usr/bin/python. The packages in the virtualenv definitely won’t be in the system path. The following fixed this:

source myvirtualenv/activate
pip install nose
which nosetests
/home/me/myvirtualenv/bin/nosetests

回答 2

对于那些以后会发现此问题的人:如果__init__.py我的tests目录中没有文件,则会出现导入错误。

我的目录结构是这样的:

./tests/
  ./test_some_random_stuff.py

如果我进行了鼻子测试:

nosetests -w tests

它会给ImportError其他人看到的。如果我添加一个空白__init__.py文件,则可以正常工作:

./tests/
  ./__init__.py
  ./test_some_random_stuff.py

To those of you finding this question later on: I get the import error if I don’t have an __init__.py file in my tests directory.

My directory structure was like this:

./tests/
  ./test_some_random_stuff.py

If I ran nosetests:

nosetests -w tests

It would give the ImportError that everyone else is seeing. If I add a blank __init__.py file it works just fine:

./tests/
  ./__init__.py
  ./test_some_random_stuff.py

回答 3

另一个潜在的问题似乎是目录树中的连字符/破折号。我最近通过重命名目录固定鼻子导入错误的问题sub-dirsub_dir

Another potential problem appears to be hyphens/dashes in the directory tree. I recently fixed a nose ImportError issue by renaming a directory from sub-dir to sub_dir.


回答 4

当然,如果在导入的模块中存在语法错误,则会导致此错误。对我来说,当我备份一个tests文件时,这个问题浮出水面,该文件的路径与modules / tests.bak.py类似,位于与tests.py相同的目录中。另外,要处理Django应用程序中的init包/模块问题,可以运行以下命令(在bash / OSX shell中)以确保周围没有任何init .pyc文件:

find . -name '*.pyc' -delete

Of course if you have a syntax error in the module being imported that will cause this. For me the problem reared its head when I had a backup of a tests file with a path like module/tests.bak.py in the same directory as tests.py. Also, to deal with the init package/module problem in a Django app, you can run the following (in a bash/OSX shell) to make sure you don’t have any init.pyc files lying around:

find . -name '*.pyc' -delete

回答 5

我收到此错误消息是因为我nosetests从错误的目录运行命令。

傻了,但是发生了。

I got this error message because I run the nosetests command from the wrong directory.

Silly, but happens.


回答 6

我只是碰到另一件事可能导致这个问题:以形式命名测试testname.test.py。多余的.东西会使鼻子感到困惑,并导致它导入它不应该导入的东西。我想很明显,使用非常规的测试命名约定会破坏事情,但是我认为可能值得注意。

I just ran into one more thing that might cause this issue: naming of tests in the form testname.test.py. That extra . confounds nose and leads to it importing things it should not. I suppose it may be obvious that using unconventional test naming conventions will break things, but I thought it might be worth noting.


回答 7

例如,下面的目录结构,如果你想运行nosetestsm1m2m3以测试某些功能n.py,你应该使用from m2.m3 import ntest.py

m1
└── m2
    ├── __init__.py
    └── m3
        ├── __init__.py
        ├── n.py
        └── test
            └── test.py

For example, with the following directory structure, if you want to run nosetests in m1, m2 or m3 to test some functions in n.py, you should use from m2.m3 import n in test.py.

m1
└── m2
    ├── __init__.py
    └── m3
        ├── __init__.py
        ├── n.py
        └── test
            └── test.py

回答 8

只需完成一个问题:如果您正在为这样的结构而苦苦挣扎:

project
├── m1
    ├── __init__.py
    ├── foo1.py
    └──m2
       ├── __init__.py
       └── foo2.py

└── test
     ├── __init__.py
     └── test.py

也许您想从项目外部的路径运行测试,将项目路径包含在PYTHONPATH中。

export PYTHONPATH=$PYTHONPATH:$HOME/path/to/project

将其粘贴到您的.profile中。如果您处于虚拟环境中,请将其粘贴到venv根目录中的Activate中

Just to complete the question: If you’re struggling with structure like this:

project
├── m1
├    ├── __init__.py
├    ├── foo1.py
├    └──m2
├       ├── __init__.py
├       └── foo2.py
├
└── test
     ├── __init__.py
     └── test.py

And maybe you want to run test from a path outside the project, include your project path inside your PYTHONPATH.

export PYTHONPATH=$PYTHONPATH:$HOME/path/to/project

paste it inside your .profile. If you’re under a virtual environment, paste it inside the activate in your venv root


检查是否安装了Python软件包

问题:检查是否安装了Python软件包

检查软件包是否在Python脚本中安装的好方法是什么?我知道从解释器很容易,但是我需要在脚本中完成。

我想我可以检查安装过程中在系统上是否创建了目录,但是我觉得有更好的方法。我试图确保已安装Skype4Py软件包,如果没有,我将安装它。

我完成支票的想法

  • 检查典型安装路径中的目录
  • 尝试导入软件包,如果抛出异常,则安装软件包

What’s a good way to check if a package is installed while within a Python script? I know it’s easy from the interpreter, but I need to do it within a script.

I guess I could check if there’s a directory on the system that’s created during the installation, but I feel like there’s a better way. I’m trying to make sure the Skype4Py package is installed, and if not I’ll install it.

My ideas for accomplishing the check

  • check for a directory in the typical install path
  • try to import the package and if an exception is throw, then install package

回答 0

如果您的意思是python脚本,请执行以下操作:

Python 3.3+使用sys.modules和find_spec

import importlib.util
import sys

# For illustrative purposes.
name = 'itertools'

if name in sys.modules:
    print(f"{name!r} already in sys.modules")
elif (spec := importlib.util.find_spec(name)) is not None:
    # If you choose to perform the actual import ...
    module = importlib.util.module_from_spec(spec)
    sys.modules[name] = module
    spec.loader.exec_module(module)
    print(f"{name!r} has been imported")
else:
    print(f"can't find the {name!r} module")

Python 3:

try:
    import mymodule
except ImportError as e:
    pass  # module doesn't exist, deal with it.

Python 2:

try:
    import mymodule
except ImportError, e:
    pass  # module doesn't exist, deal with it.

If you mean a python script, just do something like this:

Python 3.3+ use sys.modules and find_spec:

import importlib.util
import sys

# For illustrative purposes.
name = 'itertools'

if name in sys.modules:
    print(f"{name!r} already in sys.modules")
elif (spec := importlib.util.find_spec(name)) is not None:
    # If you choose to perform the actual import ...
    module = importlib.util.module_from_spec(spec)
    sys.modules[name] = module
    spec.loader.exec_module(module)
    print(f"{name!r} has been imported")
else:
    print(f"can't find the {name!r} module")

Python 3:

try:
    import mymodule
except ImportError as e:
    pass  # module doesn't exist, deal with it.

Python 2:

try:
    import mymodule
except ImportError, e:
    pass  # module doesn't exist, deal with it.

回答 1

更新的答案

更好的方法是:

import subprocess
import sys

reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze'])
installed_packages = [r.decode().split('==')[0] for r in reqs.split()]

结果:

print(installed_packages)

[
    "Django",
    "six",
    "requests",
]

检查是否requests已安装:

if 'requests' in installed_packages:
    # Do something

为什么这样呢?有时您会遇到应用名称冲突。从应用程序命名空间导入无法全面了解系统上已安装的内容。

注意,建议的解决方案有效:

  • 使用pip从PyPI或任何其他替代来源(例如pip install http://some.site/package-name.zip或任何其他存档类型)进行安装时。
  • 使用手动安装时python setup.py install
  • 从系统存储库安装时,例如sudo apt install python-requests

情况下,当它可能无法正常工作:

  • 在开发模式下安装时,例如python setup.py develop
  • 在开发模式下安装时,例如pip install -e /path/to/package/source/

旧答案

更好的方法是:

import pip
installed_packages = pip.get_installed_distributions()

对于pip> = 10.x,请使用:

from pip._internal.utils.misc import get_installed_distributions

为什么这样呢?有时您会遇到应用名称冲突。从应用程序命名空间导入无法全面了解系统上已安装的内容。

结果,您得到一个pkg_resources.Distribution对象列表。请参阅以下示例:

print installed_packages
[
    "Django 1.6.4 (/path-to-your-env/lib/python2.7/site-packages)",
    "six 1.6.1 (/path-to-your-env/lib/python2.7/site-packages)",
    "requests 2.5.0 (/path-to-your-env/lib/python2.7/site-packages)",
]

列出清单:

flat_installed_packages = [package.project_name for package in installed_packages]

[
    "Django",
    "six",
    "requests",
]

检查是否requests已安装:

if 'requests' in flat_installed_packages:
    # Do something

Updated answer

A better way of doing this is:

import subprocess
import sys

reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze'])
installed_packages = [r.decode().split('==')[0] for r in reqs.split()]

The result:

print(installed_packages)

[
    "Django",
    "six",
    "requests",
]

Check if requests is installed:

if 'requests' in installed_packages:
    # Do something

Why this way? Sometimes you have app name collisions. Importing from the app namespace doesn’t give you the full picture of what’s installed on the system.

Note, that proposed solution works:

  • When using pip to install from PyPI or from any other alternative source (like pip install http://some.site/package-name.zip or any other archive type).
  • When installing manually using python setup.py install.
  • When installing from system repositories, like sudo apt install python-requests.

Cases when it might not work:

  • When installing in development mode, like python setup.py develop.
  • When installing in development mode, like pip install -e /path/to/package/source/.

Old answer

A better way of doing this is:

import pip
installed_packages = pip.get_installed_distributions()

For pip>=10.x use:

from pip._internal.utils.misc import get_installed_distributions

Why this way? Sometimes you have app name collisions. Importing from the app namespace doesn’t give you the full picture of what’s installed on the system.

As a result, you get a list of pkg_resources.Distribution objects. See the following as an example:

print installed_packages
[
    "Django 1.6.4 (/path-to-your-env/lib/python2.7/site-packages)",
    "six 1.6.1 (/path-to-your-env/lib/python2.7/site-packages)",
    "requests 2.5.0 (/path-to-your-env/lib/python2.7/site-packages)",
]

Make a list of it:

flat_installed_packages = [package.project_name for package in installed_packages]

[
    "Django",
    "six",
    "requests",
]

Check if requests is installed:

if 'requests' in flat_installed_packages:
    # Do something

回答 2

从Python 3.3开始,您可以使用find_spec()方法

import importlib.util

# For illustrative purposes.
package_name = 'pandas'

spec = importlib.util.find_spec(package_name)
if spec is None:
    print(package_name +" is not installed")

As of Python 3.3, you can use the find_spec() method

import importlib.util

# For illustrative purposes.
package_name = 'pandas'

spec = importlib.util.find_spec(package_name)
if spec is None:
    print(package_name +" is not installed")

回答 3

如果要从终端机取支票,可以运行

pip3 show package_name

如果未返回任何内容,则表示未安装该软件包。

如果您想自动执行此检查,以便例如可以在丢失时安装它,则可以在bash脚本中包含以下内容:

pip3 show package_name 1>/dev/null #pip for Python 2
if [ $? == 0 ]; then
   echo "Installed" #Replace with your actions
else
   echo "Not Installed" #Replace with your actions, 'pip3 install --upgrade package_name' ?
fi

If you want to have the check from the terminal, you can run

pip3 show package_name

and if nothing is returned, the package is not installed.

If perhaps you want to automate this check, so that for example you can install it if missing, you can have the following in your bash script:

pip3 show package_name 1>/dev/null #pip for Python 2
if [ $? == 0 ]; then
   echo "Installed" #Replace with your actions
else
   echo "Not Installed" #Replace with your actions, 'pip3 install --upgrade package_name' ?
fi

回答 4

作为此答案的扩展:

对于Python 2. *,pip show <package_name>将执行相同的任务。

例如pip show numpy将返回以下内容:

Name: numpy
Version: 1.11.1
Summary: NumPy: array processing for numbers, strings, records, and objects.
Home-page: http://www.numpy.org
Author: NumPy Developers
Author-email: numpy-discussion@scipy.org
License: BSD
Location: /home/***/anaconda2/lib/python2.7/site-packages
Requires: 
Required-by: smop, pandas, tables, spectrum, seaborn, patsy, odo, numpy-stl, numba, nfft, netCDF4, MDAnalysis, matplotlib, h5py, GridDataFormats, dynd, datashape, Bottleneck, blaze, astropy

As an extension of this answer:

For Python 2.*, pip show <package_name> will perform the same task.

For example pip show numpy will return the following or alike:

Name: numpy
Version: 1.11.1
Summary: NumPy: array processing for numbers, strings, records, and objects.
Home-page: http://www.numpy.org
Author: NumPy Developers
Author-email: numpy-discussion@scipy.org
License: BSD
Location: /home/***/anaconda2/lib/python2.7/site-packages
Requires: 
Required-by: smop, pandas, tables, spectrum, seaborn, patsy, odo, numpy-stl, numba, nfft, netCDF4, MDAnalysis, matplotlib, h5py, GridDataFormats, dynd, datashape, Bottleneck, blaze, astropy

回答 5

您可以使用setuptools中的pkg_resources模块。例如:

import pkg_resources

package_name = 'cool_package'
try:
    cool_package_dist_info = pkg_resources.get_distribution(package_name)
except pkg_resources.DistributionNotFound:
    print('{} not installed'.format(package_name))
else:
    print(cool_package_dist_info)

请注意,python模块和python包之间有区别。一个软件包可以包含多个模块,并且模块名称可能与软件包名称不匹配。

You can use the pkg_resources module from setuptools. For example:

import pkg_resources

package_name = 'cool_package'
try:
    cool_package_dist_info = pkg_resources.get_distribution(package_name)
except pkg_resources.DistributionNotFound:
    print('{} not installed'.format(package_name))
else:
    print(cool_package_dist_info)

Note that there is a difference between python module and a python package. A package can contain multiple modules and module’s names might not match the package name.


回答 6

打开命令提示符类型

pip3 list

Open your command prompt type

pip3 list

回答 7

我想对此主题添加一些想法/发现。我正在编写一个脚本,检查定制程序的所有要求。python模块也有很多检查。

有一个小问题

try:
   import ..
except:
   ..

解。在我的情况下,其中一个python模块称为python-nmap,但是您使用导入了它,import nmap并且看到名称不匹配。因此,使用上述解决方案进行的测试将返回False结果,并且还会在命中时导入该模块,但对于简单的测试/检查,可能无需使用大量内存。

我也发现

import pip
installed_packages = pip.get_installed_distributions()

installed_packages只有pip安装了软件包。在我的系统上,pip freeze通过40python模块返回,而installed_packages只有1,我手动安装了该模块(python-nmap)。

下面我知道的另一种解决方案可能与该问题无关,但是我认为将测试功能与执行安装的功能分开是一种很好的做法,这可能对某些人有用。

对我有用的解决方案。它基于此答案如何在不导入的情况下检查python模块是否存在

from imp import find_module

def checkPythonmod(mod):
    try:
        op = find_module(mod)
        return True
    except ImportError:
        return False

注意:此解决方案也无法通过名称找到模块python-nmap,我必须nmap改用(易于使用),但是在这种情况下,模块将不会加载到内存中。

I’d like to add some thoughts/findings of mine to this topic. I’m writing a script that checks all requirements for a custom made program. There are many checks with python modules too.

There’s a little issue with the

try:
   import ..
except:
   ..

solution. In my case one of the python modules called python-nmap, but you import it with import nmap and as you see the names mismatch. Therefore the test with the above solution returns a False result, and it also imports the module on hit, but maybe no need to use a lot of memory for a simple test/check.

I also found that

import pip
installed_packages = pip.get_installed_distributions()

installed_packages will have only the packages has been installed with pip. On my system pip freeze returns over 40 python modules, while installed_packages has only 1, the one I installed manually (python-nmap).

Another solution below that I know it may not relevant to the question, but I think it’s a good practice to keep the test function separate from the one that performs the install it might be useful for some.

The solution that worked for me. It based on this answer How to check if a python module exists without importing it

from imp import find_module

def checkPythonmod(mod):
    try:
        op = find_module(mod)
        return True
    except ImportError:
        return False

NOTE: this solution can’t find the module by the name python-nmap too, I have to use nmap instead (easy to live with) but in this case the module won’t be loaded to the memory whatsoever.


回答 8

如果您希望脚本安装缺少的软件包并继续,则可以执行以下操作(在“ python-krbV”软件包中的“ krbV”模块示例中):

import pip
import sys

for m, pkg in [('krbV', 'python-krbV')]:
    try:
        setattr(sys.modules[__name__], m, __import__(m))
    except ImportError:
        pip.main(['install', pkg])
        setattr(sys.modules[__name__], m, __import__(m))

If you’d like your script to install missing packages and continue, you could do something like this (on example of ‘krbV’ module in ‘python-krbV’ package):

import pip
import sys

for m, pkg in [('krbV', 'python-krbV')]:
    try:
        setattr(sys.modules[__name__], m, __import__(m))
    except ImportError:
        pip.main(['install', pkg])
        setattr(sys.modules[__name__], m, __import__(m))

回答 9

一种快速的方法是使用python命令行工具。只需键入,import <your module name> 如果缺少模块,则会看到错误。

$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
>>> import sys
>>> import jocker
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named jocker
$

A quick way is to use python command line tool. Simply type import <your module name> You see an error if module is missing.

$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
>>> import sys
>>> import jocker
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named jocker
$

回答 10

嗯…我看到的最方便的答案是使用命令行尝试导入。但我什至宁愿避免这种情况。

冻结点如何?grep pkgname’?我试过了,效果很好。它还显示了它具有的版本以及是在版本控制(安装)下还是可编辑(开发)下安装的。

Hmmm … the closest I saw to a convenient answer was using the command line to try the import. But I prefer to even avoid that.

How about ‘pip freeze | grep pkgname’? I tried it and it works well. It also shows you the version it has and whether it is installed under version control (install) or editable (develop).


回答 11

类myError(exception):通过#或做一些尝试:导入mymodule,除了ImportError,例如e:提高myError(“发生错误”)

You can use this:

class myError(exception):
 pass # Or do some thing like this.
try:
 import mymodule
except ImportError as e:
 raise myError("error was occurred")

回答 12

在终端类型

pip show some_package_name

pip show matplotlib

In the Terminal type

pip show some_package_name

Example

pip show matplotlib

回答 13

我想评论@ ice.nicer的回复,但我不能,所以… 我的观察是带有破折号的软件包都带有下划线,而不仅仅是@dwich注释所指出的点。

例如,您这样做pip3 install sphinx-rtd-theme,但是:

  • importlib.util.find_spec(sphinx_rtd_theme) 返回一个对象
  • importlib.util.find_spec(sphinx-rtd-theme) 不返回
  • importlib.util.find_spec(sphinx.rtd.theme) 引发ModuleNotFoundError

此外,某些名称已完全更改。例如,您这样做,pip3 install pyyaml但是将其另存为yaml

我正在使用python3.8

I would like to comment to @ice.nicer reply but I cannot, so … My observations is that packages with dashes are saved with underscores, not only with dots as pointed out by @dwich comment

For example, you do pip3 install sphinx-rtd-theme, but:

  • importlib.util.find_spec(sphinx_rtd_theme) returns an Object
  • importlib.util.find_spec(sphinx-rtd-theme) returns None
  • importlib.util.find_spec(sphinx.rtd.theme) raises ModuleNotFoundError

Moreover, some names are totally changed. For example, you do pip3 install pyyaml but it is saved simply as yaml

I am using python3.8


回答 14

if pip3 list | grep -sE '^some_command\s+[0-9]' >/dev/null
  # installed ...
else
  # not installed ...
fi
if pip3 list | grep -sE '^some_command\s+[0-9]' >/dev/null
  # installed ...
else
  # not installed ...
fi

回答 15

转到选项2。如果ImportError抛出该错误,则表示未安装该软件包(或未安装sys.path)。

Go option #2. If ImportError is thrown, then the package is not installed (or not in sys.path).


导入模块中全局变量的可见性

问题:导入模块中全局变量的可见性

我在使用Python脚本导入模块时遇到了一些麻烦。我将尽力描述错误,为什么会遇到错误以及为什么要使用这种特殊方法来解决我的问题(我将在稍后描述):

假设我有一个模块,其中定义了一些实用程序函数/类,这些函数/类引用在此辅助模块将导入到的命名空间中定义的实体(让“ a”是这样的实体):

模块1:

def f():
    print a

然后,我有了主程序,其中定义了“ a”,我要将这些实用程序导入其中:

import module1
a=3
module1.f()

执行该程序将触发以下错误:

Traceback (most recent call last):
  File "Z:\Python\main.py", line 10, in <module>
    module1.f()
  File "Z:\Python\module1.py", line 3, in f
    print a
NameError: global name 'a' is not defined

过去(两天前,d’uh)曾提出类似的问题,并提出了几种解决方案,但是我真的不认为这些符合我的要求。这是我的特定情况:

我正在尝试制作一个Python程序,该程序连接到MySQL数据库服务器并使用GUI显示/修改数据。为了简洁起见,我在一个单独的文件中定义了一堆与MySQL相关的辅助/实用程序功能。但是它们都有一个公共变量,该变量是我最初实用程序模块中定义的,并且是MySQLdb模块中的游标对象。后来我意识到,游标对象(用于与db服务器通信的对象)应该在主模块中定义,以便主模块和导入到其中的所有对象都可以访问该对象。

最终结果将是这样的:

utilities_module.py:

def utility_1(args):
    code which references a variable named "cur"
def utility_n(args):
    etcetera

而我的主要模块:

program.py:

import MySQLdb, Tkinter
db=MySQLdb.connect(#blahblah) ; cur=db.cursor()  #cur is defined!
from utilities_module import *

然后,一旦我尝试调用任何实用程序函数,就会触发上述“未定义全局名称”错误。

一个特别的建议是在实用程序文件中有一个“ from program import cur”语句,例如:

utilities_module.py:

from program import cur
#rest of function definitions

program.py:

import Tkinter, MySQLdb
db=MySQLdb.connect(#blahblah) ; cur=db.cursor()  #cur is defined!
from utilities_module import *

但这是循环导入或类似的操作,最重要的是,它也崩溃了。所以我的问题是:

我该如何在主模块中定义的“ cur”对象对导入到其中的辅助功能可见?

如果您将解决方案发布在其他位置,则感谢您的宝贵时间和最深切的歉意。我只是自己找不到答案,而且我的书中没有其他花招。

I’ve run into a bit of a wall importing modules in a Python script. I’ll do my best to describe the error, why I run into it, and why I’m tying this particular approach to solve my problem (which I will describe in a second):

Let’s suppose I have a module in which I’ve defined some utility functions/classes, which refer to entities defined in the namespace into which this auxiliary module will be imported (let “a” be such an entity):

module1:

def f():
    print a

And then I have the main program, where “a” is defined, into which I want to import those utilities:

import module1
a=3
module1.f()

Executing the program will trigger the following error:

Traceback (most recent call last):
  File "Z:\Python\main.py", line 10, in <module>
    module1.f()
  File "Z:\Python\module1.py", line 3, in f
    print a
NameError: global name 'a' is not defined

Similar questions have been asked in the past (two days ago, d’uh) and several solutions have been suggested, however I don’t really think these fit my requirements. Here’s my particular context:

I’m trying to make a Python program which connects to a MySQL database server and displays/modifies data with a GUI. For cleanliness sake, I’ve defined the bunch of auxiliary/utility MySQL-related functions in a separate file. However they all have a common variable, which I had originally defined inside the utilities module, and which is the cursor object from MySQLdb module. I later realised that the cursor object (which is used to communicate with the db server) should be defined in the main module, so that both the main module and anything that is imported into it can access that object.

End result would be something like this:

utilities_module.py:

def utility_1(args):
    code which references a variable named "cur"
def utility_n(args):
    etcetera

And my main module:

program.py:

import MySQLdb, Tkinter
db=MySQLdb.connect(#blahblah) ; cur=db.cursor()  #cur is defined!
from utilities_module import *

And then, as soon as I try to call any of the utilities functions, it triggers the aforementioned “global name not defined” error.

A particular suggestion was to have a “from program import cur” statement in the utilities file, such as this:

utilities_module.py:

from program import cur
#rest of function definitions

program.py:

import Tkinter, MySQLdb
db=MySQLdb.connect(#blahblah) ; cur=db.cursor()  #cur is defined!
from utilities_module import *

But that’s cyclic import or something like that and, bottom line, it crashes too. So my question is:

How in hell can I make the “cur” object, defined in the main module, visible to those auxiliary functions which are imported into it?

Thanks for your time and my deepest apologies if the solution has been posted elsewhere. I just can’t find the answer myself and I’ve got no more tricks in my book.


回答 0

Python中的全局变量是模块的全局变量,而不是所有模块的全局变量。(许多人对此感到困惑,因为在C语言中,除非您明确创建全局变量,否则所有实现文件中的全局变量都是相同的static。)

有多种解决方法,具体取决于您的实际用例。


在走这条路之前,请问自己这是否真的需要是全球性的。也许您真的想要一个带有f实例方法的类,而不仅仅是一个自由函数?然后,您可以执行以下操作:

import module1
thingy1 = module1.Thingy(a=3)
thingy1.f()

如果您确实确实想要一个全局变量,但是它只是供您使用module1,请在该模块中进行设置。

import module1
module1.a=3
module1.f()

另一方面,如果a由许多模块共享,则将其放置在其他位置,并让每个人都将其导入:

import shared_stuff
import module1
shared_stuff.a = 3
module1.f()

…并且,在module1.py中:

import shared_stuff
def f():
    print shared_stuff.a

from除非变量打算是一个常量,否则不要使用导入。from shared_stuff import a会创建一个新a变量,初始化为shared_stuff.a导入时所引用的变量,并且该新a变量将不受分配的影响shared_stuff.a


或者,在极少数情况下,您确实确实需要它在任何地方都具有真正的全局性(例如内置),将其添加到内置模块中。确切的细节在Python 2.x和3.x之间有所不同。在3.x中,它的工作方式如下:

import builtins
import module1
builtins.a = 3
module1.f()

Globals in Python are global to a module, not across all modules. (Many people are confused by this, because in, say, C, a global is the same across all implementation files unless you explicitly make it static.)

There are different ways to solve this, depending on your actual use case.


Before even going down this path, ask yourself whether this really needs to be global. Maybe you really want a class, with f as an instance method, rather than just a free function? Then you could do something like this:

import module1
thingy1 = module1.Thingy(a=3)
thingy1.f()

If you really do want a global, but it’s just there to be used by module1, set it in that module.

import module1
module1.a=3
module1.f()

On the other hand, if a is shared by a whole lot of modules, put it somewhere else, and have everyone import it:

import shared_stuff
import module1
shared_stuff.a = 3
module1.f()

… and, in module1.py:

import shared_stuff
def f():
    print shared_stuff.a

Don’t use a from import unless the variable is intended to be a constant. from shared_stuff import a would create a new a variable initialized to whatever shared_stuff.a referred to at the time of the import, and this new a variable would not be affected by assignments to shared_stuff.a.


Or, in the rare case that you really do need it to be truly global everywhere, like a builtin, add it to the builtin module. The exact details differ between Python 2.x and 3.x. In 3.x, it works like this:

import builtins
import module1
builtins.a = 3
module1.f()

回答 1

解决方法是,您可以考虑像这样在外层设置环境变量。

main.py:

import os
os.environ['MYVAL'] = str(myintvariable)

mymodule.py:

import os

myval = None
if 'MYVAL' in os.environ:
    myval = os.environ['MYVAL']

作为额外的预防措施,请在模块内部未定义MYVAL的情况下进行处理。

As a workaround, you could consider setting environment variables in the outer layer, like this.

main.py:

import os
os.environ['MYVAL'] = str(myintvariable)

mymodule.py:

import os

myval = None
if 'MYVAL' in os.environ:
    myval = os.environ['MYVAL']

As an extra precaution, handle the case when MYVAL is not defined inside the module.


回答 2

函数使用其定义模块的全局变量。a = 3例如,应该设置而不是set module1.a = 3。因此,如果要cur用作全局输入utilities_module,请设置utilities_module.cur

更好的解决方案:不要使用全局变量。将所需的变量传递到需要它的函数中,或者创建一个类将所有数据捆绑在一起,并在初始化实例时传递它。

A function uses the globals of the module it’s defined in. Instead of setting a = 3, for example, you should be setting module1.a = 3. So, if you want cur available as a global in utilities_module, set utilities_module.cur.

A better solution: don’t use globals. Pass the variables you need into the functions that need it, or create a class to bundle all the data together, and pass it when initializing the instance.


回答 3

这篇文章只是我遇到的Python行为的观察。如果您做的事情与我在下面做的相同,则上面阅读的建议可能对您不起作用。

即,我有一个包含全局/共享变量的模块(如上所述):

#sharedstuff.py

globaltimes_randomnode=[]
globalist_randomnode=[]

然后,我有一个主要模块,用于导入共享内容:

import sharedstuff as shared

以及实际填充这些数组的其他一些模块。这些由主模块调用。当退出这些其他模块时,我可以清楚地看到已填充了阵列。但是,当在主模块中重新读取它们时,它们为空。这对我来说很奇怪(嗯,我是Python的新手)。但是,当我将主模块中的sharedstuff.py导入方式更改为:

from globals import *

它有效(填充了数组)。

只是在说’

This post is just an observation for Python behaviour I encountered. Maybe the advices you read above don’t work for you if you made the same thing I did below.

Namely, I have a module which contains global/shared variables (as suggested above):

#sharedstuff.py

globaltimes_randomnode=[]
globalist_randomnode=[]

Then I had the main module which imports the shared stuff with:

import sharedstuff as shared

and some other modules that actually populated these arrays. These are called by the main module. When exiting these other modules I can clearly see that the arrays are populated. But when reading them back in the main module, they were empty. This was rather strange for me (well, I am new to Python). However, when I change the way I import the sharedstuff.py in the main module to:

from globals import *

it worked (the arrays were populated).

Just sayin’


回答 4

解决此特定问题的最简单方法是在模块内添加另一个功能,该功能会将光标存储在模块的全局变量中。然后所有其他功能也可以使用它。

模块1:

cursor = None

def setCursor(cur):
    global cursor
    cursor = cur

def method(some, args):
    global cursor
    do_stuff(cursor, some, args)

主程序:

import module1

cursor = get_a_cursor()
module1.setCursor(cursor)
module1.method()

The easiest solution to this particular problem would have been to add another function within the module that would have stored the cursor in a variable global to the module. Then all the other functions could use it as well.

module1:

cursor = None

def setCursor(cur):
    global cursor
    cursor = cur

def method(some, args):
    global cursor
    do_stuff(cursor, some, args)

main program:

import module1

cursor = get_a_cursor()
module1.setCursor(cursor)
module1.method()

回答 5

由于全局变量是特定于模块的,因此可以将以下函数添加到所有导入的模块中,然后将其用于:

  • 将单数变量(以字典格式)添加为这些变量的全局变量
  • 将您的模块全局变量传递给它。

addglobals = lambda x:globals()。update(x)

然后,您需要传递当前的全局变量是:

导入模块

module.addglobals(globals())

Since globals are module specific, you can add the following function to all imported modules, and then use it to:

  • Add singular variables (in dictionary format) as globals for those
  • Transfer your main module globals to it .

addglobals = lambda x: globals().update(x)

Then all you need to pass on current globals is:

import module

module.addglobals(globals())


回答 6

由于我在上面的答案中没有看到它,因此我想我将添加一个简单的解决方法,global_dict即向需要调用模块全局变量的函数添加一个参数,然后在调用时将dict传递给该函数。例如:

# external_module
def imported_function(global_dict=None):
    print(global_dict["a"])


# calling_module
a = 12
from external_module import imported_function
imported_function(global_dict=globals())

>>> 12

Since I haven’t seen it in the answers above, I thought I would add my simple workaround, which is just to add a global_dict argument to the function requiring the calling module’s globals, and then pass the dict into the function when calling; e.g:

# external_module
def imported_function(global_dict=None):
    print(global_dict["a"])


# calling_module
a = 12
from external_module import imported_function
imported_function(global_dict=globals())

>>> 12

回答 7

这样做的OOP方法是使模块成为类,而不是一组未绑定的方法。然后,您可以使用__init__或setter方法来设置来自调用方的变量,以用于模块方法中。

The OOP way of doing this would be to make your module a class instead of a set of unbound methods. Then you could use __init__ or a setter method to set the variables from the caller for use in the module methods.


Python:相对于当前正在运行的脚本添加到sys.path的最佳方法

问题:Python:相对于当前正在运行的脚本添加到sys.path的最佳方法

我有一个充满脚本的目录(假设project/bin)。我也有一个图书馆project/lib,希望脚本自动加载它。这是我通常在每个脚本顶部使用的内容:

#!/usr/bin/python
from os.path import dirname, realpath, sep, pardir
import sys
sys.path.append(dirname(realpath(__file__)) + sep + pardir + sep + "lib")

# ... now the real code
import mylib

这有点麻烦,丑陋,必须粘贴在每个文件的开头。有一个更好的方法吗?

确实,我希望如此平稳:

#!/usr/bin/python
import sys.path
from os.path import pardir, sep
sys.path.append_relative(pardir + sep + "lib")

import mylib

甚至更好的是,当我的编辑器(或其他拥有提交访问权限的人)决定在其清理过程中对导入进行重新排序时,这些不会中断:

#!/usr/bin/python --relpath_append ../lib
import mylib

那不会直接移植到非posix平台,但是可以保持干净。

I have a directory full of scripts (let’s say project/bin). I also have a library located in project/lib and want the scripts to automatically load it. This is what I normally use at the top of each script:

#!/usr/bin/python
from os.path import dirname, realpath, sep, pardir
import sys
sys.path.append(dirname(realpath(__file__)) + sep + pardir + sep + "lib")

# ... now the real code
import mylib

This is kind of cumbersome, ugly, and has to be pasted at the beginning of every file. Is there a better way to do this?

Really what I’m hoping for is something as smooth as this:

#!/usr/bin/python
import sys.path
from os.path import pardir, sep
sys.path.append_relative(pardir + sep + "lib")

import mylib

Or even better, something that wouldn’t break when my editor (or someone else who has commit access) decides to reorder the imports as part of its clean-up process:

#!/usr/bin/python --relpath_append ../lib
import mylib

That wouldn’t port directly to non-posix platforms, but it would keep things clean.


回答 0

如果您不想编辑每个文件

  • 安装你的资料库像一个正常的Python libray
  • 设置PYTHONPATH为您的lib

或者如果您愿意在每个文件中添加一行,则在顶部添加导入语句,例如

import import_my_lib

保持import_my_lib.py在bin中,import_my_lib可以正确地将python路径设置为lib您想要的任何内容

If you don’t want to edit each file

  • Install you library like a normal python libray
    or
  • Set PYTHONPATH to your lib

or if you are willing to add a single line to each file, add a import statement at top e.g.

import import_my_lib

keep import_my_lib.py in bin and import_my_lib can correctly set the python path to whatever lib you want


回答 1

这是我用的:

import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), "lib"))

This is what I use:

import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), "lib"))

回答 2

我正在使用:

import sys,os
sys.path.append(os.getcwd())

I’m using:

import sys,os
sys.path.append(os.getcwd())

回答 3

创建一个包装器模块project/bin/lib,其中包含以下内容:

import sys, os

sys.path.insert(0, os.path.join(
    os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib'))

import mylib

del sys.path[0], sys, os

然后,您可以将脚本顶部的所有残骸替换为:

#!/usr/bin/python
from lib import mylib

Create a wrapper module project/bin/lib, which contains this:

import sys, os

sys.path.insert(0, os.path.join(
    os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib'))

import mylib

del sys.path[0], sys, os

Then you can replace all the cruft at the top of your scripts with:

#!/usr/bin/python
from lib import mylib

回答 4

如果您不想以任何方式更改脚本内容,请在当前工作目录之前.添加$ PYTHONPATH(请参见下面的示例)

PYTHONPATH=.:$PYTHONPATH alembic revision --autogenerate -m "First revision"

并称之为一天!

If you don’t want to change the script content in any ways, prepend the current working directory . to $PYTHONPATH (see example below)

PYTHONPATH=.:$PYTHONPATH alembic revision --autogenerate -m "First revision"

And call it a day!


回答 5

使用python 3.4+
禁止使用cx_freeze或在IDLE中使用。😃

import sys
from pathlib import Path

sys.path.append(Path(__file__).parent / "lib")

Using python 3.4+
Barring the use of cx_freeze or using in IDLE. 😃

import sys
from pathlib import Path

sys.path.append(Path(__file__).parent / "lib")

回答 6

您可以python -m从相关的根目录运行脚本。并传递“模块路径”作为参数。

例: $ python -m module.sub_module.main # Notice there is no '.py' at the end.


另一个例子:

$ tree  # Given this file structure
.
├── bar
   ├── __init__.py
   └── mod.py
└── foo
    ├── __init__.py
    └── main.py

$ cat foo/main.py
from bar.mod import print1
print1()

$ cat bar/mod.py
def print1():
    print('In bar/mod.py')

$ python foo/main.py  # This gives an error
Traceback (most recent call last):
  File "foo/main.py", line 1, in <module>
    from bar.mod import print1
ImportError: No module named bar.mod

$ python -m foo.main  # But this succeeds
In bar/mod.py

You can run the script with python -m from the relevant root dir. And pass the “modules path” as argument.

Example: $ python -m module.sub_module.main # Notice there is no '.py' at the end.


Another example:

$ tree  # Given this file structure
.
├── bar
│   ├── __init__.py
│   └── mod.py
└── foo
    ├── __init__.py
    └── main.py

$ cat foo/main.py
from bar.mod import print1
print1()

$ cat bar/mod.py
def print1():
    print('In bar/mod.py')

$ python foo/main.py  # This gives an error
Traceback (most recent call last):
  File "foo/main.py", line 1, in <module>
    from bar.mod import print1
ImportError: No module named bar.mod

$ python -m foo.main  # But this succeeds
In bar/mod.py

回答 7

提供的每个答案都存在一个问题,可以概括为“仅将这种神奇的咒语添加到脚本的开头。看看仅用一两行代码就可以做什么”。他们不会在所有可能的情况下工作!

例如,这样一种神奇的咒语使用file。不幸的是,如果使用cx_Freeze打包脚本​​或使用IDLE,则将导致异常。

另一种神奇的咒语使用os.getcwd()。仅当您从命令提示符运行脚本并且包含脚本的目录是当前工作目录(即在运行脚本之前使用cd命令切换到该目录)时,这才起作用。上帝啊!我希望我不必解释为什么如果您的Python脚本位于PATH中的某个位置,而您只需键入脚本文件的名称来运行它,为什么这将不起作用。

幸运的是,在我测试过的所有情况下,魔咒都会起作用。不幸的是,魔咒不仅仅是一两行代码。

import inspect
import os
import sys

# Add script directory to sys.path.
# This is complicated due to the fact that __file__ is not always defined.

def GetScriptDirectory():
    if hasattr(GetScriptDirectory, "dir"):
        return GetScriptDirectory.dir
    module_path = ""
    try:
        # The easy way. Just use __file__.
        # Unfortunately, __file__ is not available when cx_freeze is used or in IDLE.
        module_path = __file__
    except NameError:
        if len(sys.argv) > 0 and len(sys.argv[0]) > 0 and os.path.isabs(sys.argv[0]):
            module_path = sys.argv[0]
        else:
            module_path = os.path.abspath(inspect.getfile(GetScriptDirectory))
            if not os.path.exists(module_path):
                # If cx_freeze is used the value of the module_path variable at this point is in the following format.
                # {PathToExeFile}\{NameOfPythonSourceFile}. This makes it necessary to strip off the file name to get the correct
                # path.
                module_path = os.path.dirname(module_path)
    GetScriptDirectory.dir = os.path.dirname(module_path)
    return GetScriptDirectory.dir

sys.path.append(os.path.join(GetScriptDirectory(), "lib"))
print(GetScriptDirectory())
print(sys.path)

如您所见,这绝非易事!

There is a problem with every answer provided that can be summarized as “just add this magical incantation to the beginning of your script. See what you can do with just a line or two of code.” They will not work in every possible situation!

For example, one such magical incantation uses file. Unfortunately, if you package your script using cx_Freeze or you are using IDLE, this will result in an exception.

Another such magical incantation uses os.getcwd(). This will only work if you are running your script from the command prompt and the directory containing your script is the current working directory (that is you used the cd command to change into the directory prior to running the script). Eh gods! I hope I do not have to explain why this will not work if your Python script is in the PATH somewhere and you ran it by simply typing the name of your script file.

Fortunately, there is a magical incantation that will work in all the cases I have tested. Unfortunately, the magical incantation is more than just a line or two of code.

import inspect
import os
import sys

# Add script directory to sys.path.
# This is complicated due to the fact that __file__ is not always defined.

def GetScriptDirectory():
    if hasattr(GetScriptDirectory, "dir"):
        return GetScriptDirectory.dir
    module_path = ""
    try:
        # The easy way. Just use __file__.
        # Unfortunately, __file__ is not available when cx_freeze is used or in IDLE.
        module_path = __file__
    except NameError:
        if len(sys.argv) > 0 and len(sys.argv[0]) > 0 and os.path.isabs(sys.argv[0]):
            module_path = sys.argv[0]
        else:
            module_path = os.path.abspath(inspect.getfile(GetScriptDirectory))
            if not os.path.exists(module_path):
                # If cx_freeze is used the value of the module_path variable at this point is in the following format.
                # {PathToExeFile}\{NameOfPythonSourceFile}. This makes it necessary to strip off the file name to get the correct
                # path.
                module_path = os.path.dirname(module_path)
    GetScriptDirectory.dir = os.path.dirname(module_path)
    return GetScriptDirectory.dir

sys.path.append(os.path.join(GetScriptDirectory(), "lib"))
print(GetScriptDirectory())
print(sys.path)

As you can see, this is no easy task!


回答 8

这个最适合我。用:

os.path.abspath('')

在Mac上,它应打印如下内容:

'/Users/<your username>/<path_to_where_you_at>'

为了获得到当前wd的绝对路径,这是更好的方法,因为现在您可以根据需要向上走,如下所示:

os.path.abspath('../')

现在:

 '/Users/<your username>/'

因此,如果您想utils从这里导入,'/Users/<your username>/'
剩下要做的就是:

import sys
sys.path.append(os.path.abspath('../'))

This one works best for me. Use:

os.path.abspath('')

On mac it should print something like:

'/Users/<your username>/<path_to_where_you_at>'

To get the abs path to the current wd, this one is better because now you can go up if you want, like this:

os.path.abspath('../')

And now:

 '/Users/<your username>/'

So if you wanna import utils from here '/Users/<your username>/'
All you’ve got left to do is:

import sys
sys.path.append(os.path.abspath('../'))

回答 9

在您的示例中,我看到了一个爆炸。如果您将bin脚本运行为./bin/foo.py,而不是python ./bin/foo.py,则可以选择使用shebang更改$PYTHONPATH变量。

但是您不能直接在shebang中更改环境变量,因此您将需要一个小的帮助程序脚本。将此python.sh放入您的bin文件夹:

#!/usr/bin/env bash
export PYTHONPATH=$PWD/lib
exec "/usr/bin/python" "$@"

然后将您的shebang更改./bin/foo.py#!bin/python.sh

I see a shebang in your example. If you’re running your bin scripts as ./bin/foo.py, rather than python ./bin/foo.py, there’s an option of using the shebang to change $PYTHONPATH variable.

You can’t change environment variables directly in shebangs though, so you’ll need a small helper script. Put this python.sh into your bin folder:

#!/usr/bin/env bash
export PYTHONPATH=$PWD/lib
exec "/usr/bin/python" "$@"

And then change the shebang of your ./bin/foo.py to be #!bin/python.sh


回答 10

当我们尝试运行带有终端路径的python文件时。

import sys
#For file name
file_name=sys.argv[0]
#For first argument
dir= sys.argv[1]
print("File Name: {}, argument dir: {}".format(file_name, dir)

保存文件(test.py)。

运行系统。

打开终端并转到保存文件的那个目录。然后写

python test.py "/home/saiful/Desktop/bird.jpg"

点击进入

输出:

File Name: test, Argument dir: /home/saiful/Desktop/bird.jpg

When we try to run python file with path from terminal.

import sys
#For file name
file_name=sys.argv[0]
#For first argument
dir= sys.argv[1]
print("File Name: {}, argument dir: {}".format(file_name, dir)

Save the file (test.py).

Runing system.

Open terminal and go the that dir where is save file. then write

python test.py "/home/saiful/Desktop/bird.jpg"

Hit enter

Output:

File Name: test, Argument dir: /home/saiful/Desktop/bird.jpg

ImportError:libSM.so.6:无法打开共享库文件:没有这样的文件或目录

问题:ImportError:libSM.so.6:无法打开共享库文件:没有这样的文件或目录

尝试导入OpenCV时,使用import cv2我得到以下错误:

/usr/local/lib/python2.7/dist-packages/cv2/__init__.py in <module>()
      7 
      8 # make IDE's (PyCharm) autocompletion happy
----> 9 from .cv2 import *
     10 
     11 # wildcard import above does not import "private" variables like __version__

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

不确定如何解决-尝试使用Google的新协作工具。笔记本在这里:https : //drive.google.com/file/d/0B7-sJqBiyjCcRmFkMzl6cy1iN0k/view?usp=sharing

When trying to import OpenCV, using import cv2 I get the following error:

/usr/local/lib/python2.7/dist-packages/cv2/__init__.py in <module>()
      7 
      8 # make IDE's (PyCharm) autocompletion happy
----> 9 from .cv2 import *
     10 
     11 # wildcard import above does not import "private" variables like __version__

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

Not sure how to fix this – trying to play around with Google’s new Colaboratory tool. Notebook is here: https://drive.google.com/file/d/0B7-sJqBiyjCcRmFkMzl6cy1iN0k/view?usp=sharing


回答 0

通过将其作为脚本的前两行来解决此问题:

!pip install opencv-python
!apt update && apt install -y libsm6 libxext6
!apt-get install -y libxrender-dev

This fixed the problem by having it as the first two lines of the script:

!pip install opencv-python
!apt update && apt install -y libsm6 libxext6
!apt-get install -y libxrender-dev

回答 1

您需要添加sudo。我做了以下事情来安装它:

sudo apt-get install libsm6 libxrender1 libfontconfig1

然后这样做(可选!也许您将不需要它)

sudo python3 -m pip install opencv-contrib-python

终于完成了!

You need to add sudo . I did the following to get it installed :

sudo apt-get install libsm6 libxrender1 libfontconfig1

and then did that (optional! maybe you won’t need it)

sudo python3 -m pip install opencv-contrib-python

FINALLY got it done !


回答 2

对于CentOS,运行以下命令: sudo yum install libXext libSM libXrender

For CentOS, run this: sudo yum install libXext libSM libXrender


回答 3

现在有一个无头版本,opencv-python该版本删除了图形依赖性(如libSM)。您可以在发布页面上看到普通版/无头版(以及导致该问题GitHub问题);只需-headless在安装时添加,例如

pip install opencv-python-headless
# also contrib, if needed
pip install opencv-contrib-python-headless

There is now a headless version of opencv-python which removes the graphical dependencies (like libSM). You can see the normal / headless version on the releases page (and the GitHub issue leading to this); just add -headless when installing, e.g.,

pip install opencv-python-headless
# also contrib, if needed
pip install opencv-contrib-python-headless

回答 4

可能是您的问题 python-opencv版本。最好将您的版本降级到3.3.0.9,其中不包含任何GUI依赖项。在GitHub的此处找到了相同的问题的答案链接。

May be the problem is with your python-opencv version. It’s better to downgrade your version to 3.3.0.9 which does not include any GUI dependencies. Same question was found on GitHub here the link to the answer.


回答 5

我在python:3.7-slimdocker盒上遇到了openCV的类似问题。以下对我有用:

apt-get install build-essential libglib2.0-0 libsm6 libxext6 libxrender-dev

请查看是否有帮助!

I was facing similar issue with openCV on the python:3.7-slim docker box. Following did the trick for me :

apt-get install build-essential libglib2.0-0 libsm6 libxext6 libxrender-dev

Please see if this helps !


回答 6

我无法在Google Cloud Platform的Ubuntu上运行的Anaconda-Jupyter笔记本上安装cv2。但是我找到了一种方法,如下所示:

从ssh终端运行以下命令,并按照说明进行操作:

 sudo apt-get install libsm6 libxrender1 libfontconfig1

安装完毕后,打开Jupyter笔记本并运行以下命令:

!pip install opencv-contrib-python

注意:我尝试运行此命令:“ sudo python3 -m pip install opencv-contrib-python”,但显示错误。但是以上命令对我有用。

现在刷新笔记本页面,并通过import cv2在笔记本中运行检查它是否已安装。

I was not able to install cv2 on Anaconda-Jupyter notebook running on Ubuntu on Google Cloud Platform. But I found a way to do it as follows:

Run the following command from the ssh terminal and follow the instruction:

 sudo apt-get install libsm6 libxrender1 libfontconfig1

Once its installed Open the Jupyter notebook and run following command:

!pip install opencv-contrib-python

Note: I tried to run this command: “sudo python3 -m pip install opencv-contrib-python”but it was showing an error. But above command worked for me.

Now refresh the notebook page and check whether it’s installed or not by running import cv2 in the notebook.


回答 7

我遇到了同样的问题docker这些步骤对我有用:

apt update

然后:

apt install libsm6 libxext6 libxrender-dev

I had the same problem in docker and these steps worked for me:

apt update

then:

apt install libsm6 libxext6 libxrender-dev

PyDev和Eclipse的未解决的导入问题

问题:PyDev和Eclipse的未解决的导入问题

我对PyDev和Python还是很陌生,尽管我已经大量使用Eclipse来编写Java。我正在尝试研究一些“ Dive Into Python”示例,这感觉像一个极其琐碎的问题,变得非常烦人。我正在使用Ubuntu Linux 10.04。

我希望能够使用odbchelper.py文件,该文件位于目录中 /Desktop/Python_Tutorials/diveintopython/py

这是我在PyDev / Eclipse项目中正在使用的example.py文件:

import sys
sys.path.append("~/Desktop/Python_Tutorials/diveintopython/py")

这可以正常工作,但是然后我希望代码的下一行是:

import odbchelper

并且这每次都会导致无法解决的导入错误。我已经将__init__.py文件添加到几乎所有可能的目录中,但它无济于事。我尝试一次将__init__.py文件一次添加到项目位置和odbchelper.py文件之间的各个目录级别,并且还尝试同时将__init__.py文件添加到介于两者之间的所有目录中。都不行。

我要做的就是在其他目录中的某个地方有一个项目,例如/Desktop/MyStuff/Project,其中有example.py …,然后从example.py中导入,我想从中导入odbchelper.py/Desktop/Python_Tutorials/diveintopython/py/

我可以找到每个留言板响应,只是说要使用该sys.path.append()功能将该目录添加到我的路径,然后将其导入…,但这恰恰是我在代码中所做的,并且不起作用。

我也尝试了Ctrl1技巧来抑制错误消息,但该程序仍无法正常运行。我收到一个错误ImportError: No module named odbchelper。因此,显然没有添加路径,或者存在一些我添加__init__.py文件的所有排列都遗漏的问题。

如此简单的事情令人非常沮丧……从我的机器上其他地方存在的文件中调用事物……需要这么多的努力。

I am very new to PyDev and Python, though I have used Eclipse for Java plenty. I am trying to work through some of the Dive Into Python examples and this feels like an extremely trivial problem that’s just becoming exceedingly annoying. I am using Ubuntu Linux 10.04.

I want to be able to use the file odbchelper.py, which is located in the directory /Desktop/Python_Tutorials/diveintopython/py

Here is my example.py file that I’m working on in my PyDev/Eclipse project:

import sys
sys.path.append("~/Desktop/Python_Tutorials/diveintopython/py")

This works fine, but then I want the next line of my code to be:

import odbchelper

and this causes an unresolved import error every time. I have added __init__.py files to just about every directory possible and it doesn’t help anything. I’ve tried adding __init__.py files one at a time to the various levels of directories between the project location and the odbchelper.py file, and I’ve also tried adding the __init__.py files to all of the directories in between simultaneously. Neither works.

All I want to do is have a project somewhere in some other directory, say /Desktop/MyStuff/Project, in which I have example.py … and then from example.py I want to import odbchelper.py from /Desktop/Python_Tutorials/diveintopython/py/

Every message board response I can find just saying to use the sys.path.append() function to add this directory to my path, and then import it … but that is precisely what I am doing in my code and it’s not working.

I have also tried the Ctrl1 trick to suppress the error message, but the program is still not functioning correctly. I get an error, ImportError: No module named odbchelper. So it’s clearly not getting the path added, or there is some problem that all of my many permutations of adding __init__.py files has missed.

It’s very frustrating that something this simple… calling things from some file that exists somewhere else on my machine… requires this much effort.


回答 0

在pydev项目的属性中,有一个名为“ PyDev-PYTHONPATH”的窗格,以及一个名为“ External Libraries”的子窗格。您可以__init__.py使用该窗格将源文件夹(任何带有的文件夹)添加到路径。然后,您的项目代码将能够从那些源文件夹中导入模块。

In the properties for your pydev project, there’s a pane called “PyDev – PYTHONPATH”, with a sub-pane called “External Libraries”. You can add source folders (any folder that has an __init__.py) to the path using that pane. Your project code will then be able to import modules from those source folders.


回答 1

我正在使用eclipse kepler 4.3,PyDev 3.9.2和在Ubuntu 14.04上遇到相同的问题。我尝试并花费了数小时,使用了以上所有大多数选项,但徒劳无功。然后我尝试了以下很棒的方法:

  • 选择项目 – > RightClick-> 的PyDev – > 删除PyDev的项目配置
  • 文件-> 重新启动

我认为我使用Python 2.7作为解释器,尽管它没有作用。

I am using eclipse kepler 4.3, PyDev 3.9.2 and on my ubuntu 14.04 I encountered with the same problem. I tried and spent hours, with all the above most of the options but in vain. Then I tried the following which was great:

  • Select Project-> RightClick-> PyDev-> Remove PyDev Project Config
  • file-> restart

And I was using Python 2.7 as an interpreter, although it doesn’t effect, I think.


回答 2

我刚刚将WXWindows项目升级到Python 2.7,并且让Pydev识别新的解释器没有麻烦。进行与上述配置解释器相同的操作,重新安装了Eclipse和Pydev。以为python的某些部分一定已损坏,所以我再次重新安装了所有内容。啊!关闭并重新打开项目,然后在所有这些更改之间重新启动Eclipse。

最终注意到,您可以通过右键单击项目来“删除PyDev项目配置”。然后可以将其重新制作为PyDev项目,现在它就像金子一样好!

I just upgraded a WXWindows project to Python 2.7 and had no end of trouble getting Pydev to recognize the new interpreter. Did the same thing as above configuring the interpreter, made a fresh install of Eclipse and Pydev. Thought some part of python must have been corrupt, so I re-installed everything again. Arghh! Closed and reopened the project, and restarted Eclipse between all of these changes.

FINALLY noticed you can ‘remove the PyDev project config’ by right clicking on project. Then it can be made into a PyDev project again, now it is good as gold!


回答 3

我修复了pythonpath,当我通过控制台导入内容时,一切都变得很花哨,但是无论我重新启动eclipse或刷新/清理项目多少次,所有这些以前无法解决的导入仍被标记为我的代码中的错误。

我右键单击项目-> Pydev->删除错误标记,它摆脱了这个问题。不用担心,如果您的代码中包含实际错误,它们将被重新标记。

I fixed my pythonpath and everything was dandy when I imported stuff through the console, but all these previously unresolved imports were still marked as errors in my code, no matter how many times I restarted eclipse or refreshed/cleaned the project.

I right clicked the project->Pydev->Remove error markers and it got rid of that problem. Don’t worry, if your code contains actual errors they will be re-marked.


回答 4

项目->属性-> pydev-pythonpath->外部库->添加源文件夹,添加项目的父文件夹。然后重新启动Eclipse。

project–>properties–>pydev-pythonpath–>external libraries –> add source folder, add the PARENT FOLDER of the project. Then restart eclipse.


回答 5

这是为我工作的(由soulBit推荐):

1) Restart using restart from the file menu
2) Once it started again, manually close and open it.

这是有史以来最简单的解决方案,它完全消除了烦人的事情。

Here is what worked for me (sugested by soulBit):

1) Restart using restart from the file menu
2) Once it started again, manually close and open it.

This is the simplest solution ever and it completely removes the annoying thing.


回答 6

有两种方法可以解决此问题:

  • 从“ Python解释器”中删除Python解释器,然后再次添加。
  • 或者只是在项目中使用的解释器中添加包含库的文件夹,就我而言,我使用的是“ bottle”,添加的文件夹是“ c:\ Python33 \ Lib \ site-packages \ bottle-0.11.6 -py3.3.egg”

现在,我不再看到该错误,并且代码完成功能也可以与“瓶”一起使用。

There are two ways of solving this issue:

  • Delete the Python interpreter from “Python interpreters” and add it again.
  • Or just add the folder with the libraries in the interpreter you are using in your project, in my case I was using “bottle” and the folder I added was “c:\Python33\Lib\site-packages\bottle-0.11.6-py3.3.egg”

Now I don’t see the error anymore, and the code completion feature works as well with “bottle”.


回答 7

我正在运行Eclipse 4.2.0(Juno)和PyDev 2.8.1,并在将lib安装到我的站点软件包路径时遇到了此问题。根据这个SO问题:

Pydev和* .pyc文件

… PyDev和pyc文件存在问题。对于我尝试引用的特定库,仅提供pyc文件。

这是我为解决此问题所做的工作:

  1. https://github.com/Mysterie/uncompyle2安装uncompyle2
  2. 对site-packages库中的* .pyc文件运行uncompyle2。例:

    uncompyle2 -r -o / tmp / path / to / site-packages / lib

  3. 将由uncompyle2生成的结果* .pyc_dis文件重命名为* .py
  4. 将这些* .py文件移动/复制到站点软件包路径
  5. 在Eclipse中,选择File> Restart

与.pyc文件有关的未解决的导入错误现在应该消失了。

I’m running Eclipse 4.2.0 (Juno) and PyDev 2.8.1, and ran into this problem with a lib installed to my site-packages path. According to this SO question:

Pydev and *.pyc Files

…there is an issue with PyDev and pyc files. In the case of the particular lib I tried to reference, all that is delivered is pyc files.

Here’s what I did to address this:

  1. Install uncompyle2 from https://github.com/Mysterie/uncompyle2
  2. Run uncompyle2 against the *.pyc files in the site-packages lib. Example:

    uncompyle2 -r -o /tmp /path/to/site-packages/lib

  3. Rename the resulting *.pyc_dis files produced from uncompyle2 to *.py
  4. Move / copy these *.py files to the site-packages path
  5. In Eclipse, select File > Restart

The unresolved import error relating to .pyc files should now disappear.


回答 8

以下,我认为会解决问题

  1. init .py 添加到“〜/ Desktop / Python_Tutorials / diveintopython / py”文件夹中
  2. 转到窗口->首选项-> PyDev->解释器-> Python解释器以删除您的Python解释器设置(原因是因为PyDev无法自动刷新对任何系统PythonPath所做的任何更新)
  3. 使用与之前相同的详细信息添加解释器(这将通过对PythonPath进行的更新来刷新Python解释器设置)
  4. 最后,由于您的“〜/ Desktop / Python_Tutorials / diveintopython / py”文件夹不是标准的PythonPath,因此需要将其添加。有两种方法可以实现

一个。按照大卫·德文的建议。但是,这仅适用于您所在的特定项目。在“窗口”->首选项-> PyDev->解释器-> Python解释器->库子选项卡-> NewFolder下,将“〜/ Desktop / Python_Tutorials / diveintopython / py”添加到新的PythonPath中

希望能帮助到你。

Following, in my opinion will solve the problem

  1. Adding the init.py to your “~/Desktop/Python_Tutorials/diveintopython/py” folder
  2. Go to Window –> Preferences –> PyDev –> Interpreters –> Python Interpreter to remove your Python Interpreter setting (reason being is because PyDev unable to auto refresh any updates made to any System PythonPath)
  3. Add in the Interpreter with the same details as before (this will refresh your Python Interpreter setting with updates made to your PythonPath)
  4. Finally since your “~/Desktop/Python_Tutorials/diveintopython/py” folder not a standard PythonPath, you will need to add it in. There are two ways to do it

a. As per what David German suggested. However this only applicable for the particular projects you are in b. Add in “~/Desktop/Python_Tutorials/diveintopython/py” into a new PythonPath under Window –> Preferences –> PyDev –> Interpreters –> Python Interpreter –> Libraries subtab –> NewFolder

Hope it helps.


回答 9

在尝试解决问题之后,通过理解PYTHONPATH,解释器和语法,我在导入其他库时遇到了一些问题,我发现我做了所有的编写,但问题仍然存在。之后,我只在出现导入错误的文件中添加一个新的空行,然后保存它们并解决了错误

I had some issues importing additional libraries, after trying to resolve the problem, by understanding PYTHONPATH, Interpreter, and Grammar I found that I did everything write but the problems continue. After that, I just add a new empty line in the files that had the import errors and saved them and the error was resolved.


回答 10

KD.py

class A:
a=10;

KD2.py 
from com.jbk.KD import A;
class B:
  b=120;

aa=A();
print(aa.a)

这对我来说很完美

另一个例子是

main.py
=======
from com.jbk.scenarios.objectcreation.settings import _init
from com.jbk.scenarios.objectcreation.subfile import stuff

_init();
stuff();

settings.py
==========
def _init():
print("kiran")


subfile.py
==========
def stuff():
print("asasas")    
KD.py

class A:
a=10;

KD2.py 
from com.jbk.KD import A;
class B:
  b=120;

aa=A();
print(aa.a)

THIS works perfectly file for me

Another example is

main.py
=======
from com.jbk.scenarios.objectcreation.settings import _init
from com.jbk.scenarios.objectcreation.subfile import stuff

_init();
stuff();

settings.py
==========
def _init():
print("kiran")


subfile.py
==========
def stuff():
print("asasas")