简体   繁体   English

在哪里保存python模块

[英]Where to save python modules

I'm just learning about modules in python 3.5. 我只是在学习python 3.5中的模块。 While I can usually install and import packages using sudo pip install {package}, I can't seem to figure out how to import my own files. 虽然我通常可以使用sudo pip install {package}安装和导入软件包,但似乎无法弄清楚如何导入自己的文件。

I made a test.py file with a single definition to test. 我制作了一个具有单个定义的test.py文件进行测试。 I saved it to the site-packages folder. 我将其保存到site-packages文件夹中。 I can't seem to import from there. 我似乎无法从那里导入。 I need help understanding how to import files. 我需要了解如何导入文件的帮助。

I read online about possibly using sys.path however, I don't know how that works. 我在网上阅读了有关可能使用sys.path的信息,但我不知道它是如何工作的。

If I had the following file structure: 如果我具有以下文件结构:

/home/foo
/home/foo/__init__.py
/home/foo/bar.py

and I wanted to 我想

import foo.bar
foo.bar.somefn()

I would first need to do: 我首先需要做的是:

import sys
sys.path.append("/home/foo")

Notice the init .py file, which tells python to look for submodules. 请注意init .py文件,该文件告诉python查找子模块。 We don't necessarily need it in this instance, but it's good practice to have: 在这种情况下,我们不一定需要它,但是具有以下优点是一种好习惯:

What is __init__.py for? __init__.py的作用是什么?

However, since this can get repetitive, daunting and tough to track, there are lots of tools available to help you setup as your code expands to have dependencies and lots of files/folders. 但是,由于这可能会导致重复,艰巨且难以跟踪,因此有很多工具可用来帮助您在代码扩展为具有依赖项和大量文件/文件夹时进行设置。 I suggest you read a bit about pip/disttools/easy-install and how to make a package with a 'setup.py'. 我建议您阅读一些有关pip / disttools / easy-install以及如何使用“ setup.py”制作软件包的信息。

What is setup.py? 什么是setup.py?

In addition, you might want to explore the world of Virtual Environments and deployment solutions such as Buildout and Anaconda. 此外,您可能想探索虚拟环境和诸如Buildout和Anaconda之类的部署解决方案的世界。 These help keep the code separated as you have several projects on the go with different needs, or even different python builds and platform requirements. 这些可以使代码分离,因为您有几个正在运行的项目有不同的需求,甚至是不同的python构建和平台要求。 When it comes time to deploy your code to other machines, you'll have a much easier time replicating the needs of the project. 当需要将代码部署到其他计算机时,您将可以轻松地复制项目的需求。

Below is a series of articles with info explaining everything from packages, pip and setup.py to starting up your work environment with Buildout. 以下是一系列带有信息的文章,其中介绍了从package,pip和setup.py到使用Buildout启动工作环境的所有内容。 Seems like a great series: 好像是一个很棒的系列:

http://reinout.vanrees.org/weblog/tags/softwarereleasesseries.html http://reinout.vanrees.org/weblog/tags/softwarereleasesseries.html

The official docs for making a setup.py: 进行setup.py的官方文档:

https://docs.python.org/3/distutils/setupscript.html https://docs.python.org/3/distutils/setupscript.html

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

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