如何导入其他 Python 文件?

发布于 2024-08-23 17:57:14 字数 152 浏览 6 评论 0原文

如何在 Python 中导入文件?我想导入:

  1. 一个文件(例如 file.py
  2. 一个文件夹
  3. 一个文件 在运行时根据用户输入动态地
  4. 导入 文件的一个特定部分(例如单个函数)

How do I import files in Python? I want to import:

  1. a file (e.g. file.py)
  2. a folder
  3. a file dynamically at runtime, based on user input
  4. one specific part of a file (e.g. a single function)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(23

水中月 2024-08-30 17:57:14

导入 python 文件的方法有很多种,各有优缺点。

不要匆忙选择第一个适合您的导入策略,否则当您发现它不能满足您的需求时,您将不得不重写代码库。

我将首先解释最简单的示例 #1,然后我将转向最专业和最强大的示例 #7

示例 1,使用 python 解释器导入 python 模块:

  1. 将其放入/home/el/foo/fox.py:

    def What_does_the_fox_say():
      print("泼妇哭了")
    
  2. 进入 python 解释器:

    el@apollo:/home/el/foo$ python
    Python 2.7.3(默认,2013 年 9 月 26 日,20:03:06) 
    >>>>>进口狐狸
    >>>>>狐狸.what_does_the_fox_say()
    狐狸精哭泣
    >>>>> 
    

    您通过Python解释器导入了fox,并从fox.py中调用了python函数what_does_the_fox_say()

示例 2,在 Python 3 中使用 execfile 或 (exec) 在脚本中执行其他 python 文件:

  1. 将其放入 /home/el/foo2/mylib.py:

    def moobar():
      打印(“嗨”)
    
  2. 将其放入 /home/el/foo2/main.py:

    execfile("/home/el/foo2/mylib.py")
    穆巴()
    
  3. 运行文件:

    el@apollo:/home/el/foo$ python main.py
    你好
    

    函数 moobar 是从 mylib.py 导入的,并在 main.py 中可用

示例 3,使用 from ... import ... 功能:

  1. 将其放入 /home/ el/foo3/chekov.py:

    def 问题():
      print("核威斯尔在哪里?")
    
  2. 将其放入 /home/el/foo3/main.py:

    来自 chekov 导入问题
    问题()
    
  3. 像这样运行:

    el@apollo:/home/el/foo3$ python main.py 
    核潜艇在哪里?
    

    如果您在 chekov.py 中定义了其他函数,除非您import *,否则它们将不可用

如果您在 chekov.py 中定义了其他函数,除非您 import * 示例 4,导入 riaa.py(如果它位于不同的文件位置),否则 它已导入

  1. 将其放入 /home/el/foo4/stuff/riaa.py:

    def watchout():
      print("计算机正在变成人类的绞索和枷锁")
    
  2. 将其放入 /home/el/foo4/main.py:

    导入系统 
    导入操作系统
    sys.path.append(os.path.abspath("/home/el/foo4/stuff"))
    从 riaa 进口 *
    小心()
    
  3. 运行它:

    el@apollo:/home/el/foo4$ python main.py 
    计算机正在变成人类的绞索和枷锁
    

    从不同的目录导入外部文件中的所有内容。

示例 5,使用 os.system("python yourfile.py")

import os
os.system("python yourfile.py")

示例 6,通过搭载 python 启动钩子导入文件:

更新:此示例曾经适用于 python2 和 3,但现在仅适用于 python2。 python3 摆脱了这个用户startuphook 功能集,因为它被低技能的Python 库编写者滥用,使用它不礼貌地将代码注入到所有用户定义程序之前的全局命名空间中。如果您希望它适用于 python3,您必须发挥更多创意。如果我告诉你如何做,Python 开发人员也会禁用该功能集,所以你只能靠自己了。

请参阅:https://docs.python.org/2/library/user.html< /a>

将此代码放入 ~/.pythonrc.py 中的主目录

class secretclass:
    def secretmessage(cls, myarg):
        return myarg + " is if.. up in the sky, the sky"
    secretmessage = classmethod( secretmessage )

    def skycake(cls):
        return "cookie and sky pie people can't go up and "
    skycake = classmethod( skycake )

将此代码放入 main.py(可以在任何地方):

import user
msg = "The only way skycake tates good" 
msg = user.secretclass.secretmessage(msg)
msg += user.secretclass.skycake()
print(msg + " have the sky pie! SKYCAKE!")

运行它,您应该得到以下结果:

$ python main.py
The only way skycake tates good is if.. up in the sky, 
the skycookie and sky pie people can't go up and  have the sky pie! 
SKYCAKE!

如果您得到这里出现错误: ModuleNotFoundError: No module named 'user' 那么这意味着您正在使用 python3,默认情况下启动钩子在那里被禁用。

此要点的功劳在于: https:// github.com/docwhat/homedir-examples/blob/master/python-commandline/.pythonrc.py 发送你的上船。

示例 7,最强大:使用裸导入命令在 python 中导入文件:

  1. 创建一个新目录 /home/el/foo5/

  2. 创建一个新目录 /home/el/foo5/herp

  3. 在herp下创建一个名为__init__.py的空文件:

    el@apollo:/home/el/foo5/herp$ touch __init__.py
    el@apollo:/home/el/foo5/herp$ ls
    __init__.py
    
  4. 创建一个新目录/home/el/foo5/herp/derp

  5. 在 derp 下,创建另一个 __init__.py 文件:

    el@apollo:/home/el/foo5/herp/derp$ touch __init__.py
    el@apollo:/home/el/foo5/herp/derp$ ls
    __init__.py
    
  6. 在 /home/el/foo5/herp/derp 下创建一个名为 yolo.py 的新文件,将其放入其中:

    def skycake():
      print("SkyCake 的发展超出了人类的认知范围" +
      “大部分男人。天空蛋糕!!”)
    
  7. 关键时刻,创建新文件 /home/el /foo5/main.py,把它放在那里;

    从herp.derp.yolo导入skycake
    天空蛋糕()
    
  8. 运行它:

    el@apollo:/home/el/foo5$ python main.py
    SkyCake 的发展超出了大多数人的认知范围 
    男人。天空蛋糕!!
    

    空的 __init__.py 文件向 python 解释器传达开发人员希望此目录成为可导入包的信息。

如果您想查看我关于如何在目录下包含所有 .py 文件的帖子,请参阅此处:https://stackoverflow.com/a /20753073/445131

There are many ways to import a python file, all with their pros and cons.

Don't just hastily pick the first import strategy that works for you or else you'll have to rewrite the codebase later on when you find it doesn't meet your needs.

I'll start out explaining the easiest example #1, then I'll move toward the most professional and robust example #7

Example 1, Import a python module with python interpreter:

  1. Put this in /home/el/foo/fox.py:

    def what_does_the_fox_say():
      print("vixens cry")
    
  2. Get into the python interpreter:

    el@apollo:/home/el/foo$ python
    Python 2.7.3 (default, Sep 26 2013, 20:03:06) 
    >>> import fox
    >>> fox.what_does_the_fox_say()
    vixens cry
    >>> 
    

    You imported fox through the python interpreter, invoked the python function what_does_the_fox_say() from within fox.py.

Example 2, Use execfile or (exec in Python 3) in a script to execute the other python file in place:

  1. Put this in /home/el/foo2/mylib.py:

    def moobar():
      print("hi")
    
  2. Put this in /home/el/foo2/main.py:

    execfile("/home/el/foo2/mylib.py")
    moobar()
    
  3. run the file:

    el@apollo:/home/el/foo$ python main.py
    hi
    

    The function moobar was imported from mylib.py and made available in main.py

Example 3, Use from ... import ... functionality:

  1. Put this in /home/el/foo3/chekov.py:

    def question():
      print("where are the nuclear wessels?")
    
  2. Put this in /home/el/foo3/main.py:

    from chekov import question
    question()
    
  3. Run it like this:

    el@apollo:/home/el/foo3$ python main.py 
    where are the nuclear wessels?
    

    If you defined other functions in chekov.py, they would not be available unless you import *

Example 4, Import riaa.py if it's in a different file location from where it is imported

  1. Put this in /home/el/foo4/stuff/riaa.py:

    def watchout():
      print("computers are transforming into a noose and a yoke for humans")
    
  2. Put this in /home/el/foo4/main.py:

    import sys 
    import os
    sys.path.append(os.path.abspath("/home/el/foo4/stuff"))
    from riaa import *
    watchout()
    
  3. Run it:

    el@apollo:/home/el/foo4$ python main.py 
    computers are transforming into a noose and a yoke for humans
    

    That imports everything in the foreign file from a different directory.

Example 5, use os.system("python yourfile.py")

import os
os.system("python yourfile.py")

Example 6, import your file via piggybacking the python startuphook:

Update: This example used to work for both python2 and 3, but now only works for python2. python3 got rid of this user startuphook feature set because it was abused by low-skill python library writers, using it to impolitely inject their code into the global namespace, before all user-defined programs. If you want this to work for python3, you'll have to get more creative. If I tell you how to do it, python developers will disable that feature set as well, so you're on your own.

See: https://docs.python.org/2/library/user.html

Put this code into your home directory in ~/.pythonrc.py

class secretclass:
    def secretmessage(cls, myarg):
        return myarg + " is if.. up in the sky, the sky"
    secretmessage = classmethod( secretmessage )

    def skycake(cls):
        return "cookie and sky pie people can't go up and "
    skycake = classmethod( skycake )

Put this code into your main.py (can be anywhere):

import user
msg = "The only way skycake tates good" 
msg = user.secretclass.secretmessage(msg)
msg += user.secretclass.skycake()
print(msg + " have the sky pie! SKYCAKE!")

Run it, you should get this:

$ python main.py
The only way skycake tates good is if.. up in the sky, 
the skycookie and sky pie people can't go up and  have the sky pie! 
SKYCAKE!

If you get an error here: ModuleNotFoundError: No module named 'user' then it means you're using python3, startuphooks are disabled there by default.

Credit for this jist goes to: https://github.com/docwhat/homedir-examples/blob/master/python-commandline/.pythonrc.py Send along your up-boats.

Example 7, Most Robust: Import files in python with the bare import command:

  1. Make a new directory /home/el/foo5/

  2. Make a new directory /home/el/foo5/herp

  3. Make an empty file named __init__.py under herp:

    el@apollo:/home/el/foo5/herp$ touch __init__.py
    el@apollo:/home/el/foo5/herp$ ls
    __init__.py
    
  4. Make a new directory /home/el/foo5/herp/derp

  5. Under derp, make another __init__.py file:

    el@apollo:/home/el/foo5/herp/derp$ touch __init__.py
    el@apollo:/home/el/foo5/herp/derp$ ls
    __init__.py
    
  6. Under /home/el/foo5/herp/derp make a new file called yolo.py Put this in there:

    def skycake():
      print("SkyCake evolves to stay just beyond the cognitive reach of " +
      "the bulk of men. SKYCAKE!!")
    
  7. The moment of truth, Make the new file /home/el/foo5/main.py, put this in there;

    from herp.derp.yolo import skycake
    skycake()
    
  8. Run it:

    el@apollo:/home/el/foo5$ python main.py
    SkyCake evolves to stay just beyond the cognitive reach of the bulk 
    of men. SKYCAKE!!
    

    The empty __init__.py file communicates to the python interpreter that the developer intends this directory to be an importable package.

If you want to see my post on how to include ALL .py files under a directory see here: https://stackoverflow.com/a/20753073/445131

澉约 2024-08-30 17:57:14

importlib 已添加到 Python 3以编程方式导入模块。

import importlib

moduleName = input('Enter module name:')
importlib.import_module(moduleName)

应从 moduleName 中删除 .py 扩展名。该函数还为相对导入定义了一个package 参数。

在 python 2.x 中:

  • 只需 import file 而不带 .py 扩展名
  • 通过添加空的 __init__.py 文件,可以将文件夹标记为包
  • 您可以使用 < code>__import__ 函数,它将模块名称(不带扩展名)作为字符串扩展
pmName = input('Enter module name:')
pm = __import__(pmName)
print(dir(pm))

名键入 help(__import__) 了解更多详细信息。

importlib was added to Python 3 to programmatically import a module.

import importlib

moduleName = input('Enter module name:')
importlib.import_module(moduleName)

The .py extension should be removed from moduleName. The function also defines a package argument for relative imports.

In python 2.x:

  • Just import file without the .py extension
  • A folder can be marked as a package, by adding an empty __init__.py file
  • You can use the __import__ function, which takes the module name (without extension) as a string extension
pmName = input('Enter module name:')
pm = __import__(pmName)
print(dir(pm))

Type help(__import__) for more details.

怎樣才叫好 2024-08-30 17:57:14

第一种情况

您想要将文件 A.py 导入到文件 B.py 中,这两个文件位于同一文件夹中,如下所示:

. 
├── A.py 
└── B.py

您可以在文件 B 中执行此操作.py:

import A

或者

from A import *

或者

from A import THINGS_YOU_WANT_TO_IMPORT_IN_A

然后你就可以在B.py>文件中使用A.py文件的所有功能


第二案例

您想在文件B.py中导入文件folder/A.py,这两个文件不在同一个文件夹中,如下所示:

.
├── B.py
└── folder
     └── A.py

您可以在文件<中执行此操作code>B.py:

import folder.A

或者

from folder.A import *

或者

from folder.A import THINGS_YOU_WANT_TO_IMPORT_IN_A

然后你就可以在B.py文件中使用A.py文件的所有功能


< strong>摘要

  • 第一种情况中,文件A.py是您在文件B中导入的模块。 py,您使用了语法import module_name
  • 第二种情况中,folder是包含模块A.py的包,您使用了语法import package_name.module_name< /代码>。

有关包和模块的更多信息,请参阅此链接

First case

You want to import file A.py in file B.py, these two files are in the same folder, like this:

. 
├── A.py 
└── B.py

You can do this in file B.py:

import A

or

from A import *

or

from A import THINGS_YOU_WANT_TO_IMPORT_IN_A

Then you will be able to use all the functions of file A.py in file B.py


Second case

You want to import file folder/A.py in file B.py, these two files are not in the same folder, like this:

.
├── B.py
└── folder
     └── A.py

You can do this in file B.py:

import folder.A

or

from folder.A import *

or

from folder.A import THINGS_YOU_WANT_TO_IMPORT_IN_A

Then you will be able to use all the functions of file A.py in file B.py


Summary

  • In the first case, file A.py is a module that you imports in file B.py, you used the syntax import module_name.
  • In the second case, folder is the package that contains the module A.py, you used the syntax import package_name.module_name.

For more info on packages and modules, consult this link.

挽清梦 2024-08-30 17:57:14

要在“运行时”导入已知名称的特定 Python 文件:

import os
import sys

...

scriptpath = "../Test/"

# Add the directory containing your module to the Python path (wants absolute paths)
sys.path.append(os.path.abspath(scriptpath))

# Do the import
import MyModule

To import a specific Python file at 'runtime' with a known name:

import os
import sys

...

scriptpath = "../Test/"

# Add the directory containing your module to the Python path (wants absolute paths)
sys.path.append(os.path.abspath(scriptpath))

# Do the import
import MyModule
此刻的回忆 2024-08-30 17:57:14

将 python 文件从一个文件夹导入到另一个文件夹的复杂方法并不多。只需创建一个 __init__.py 文件来声明此文件夹是一个 python 包,然后转到要导入的主机文件,只需键入

from root.parent.folder.file import 变量,类,无论什么

You do not have many complex methods to import a python file from one folder to another. Just create a __init__.py file to declare this folder is a python package and then go to your host file where you want to import just type

from root.parent.folder.file import variable, class, whatever

影子是时光的心 2024-08-30 17:57:14

导入文档.. -- 参考链接

__init__.py 文件是使 Python 将目录视为包含包所必需的,这样做是为了防止具有通用名称(例如字符串)的目录无意中隐藏稍后出现在模块搜索路径上的有效模块。

__init__.py 可以只是一个空文件,但它也可以执行包的初始化代码或设置 __all__ 变量。

mydir/spam/__init__.py
mydir/spam/module.py
import spam.module
or
from spam import module

Import doc .. -- Link for reference

The __init__.py files are required to make Python treat the directories as containing packages, this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

__init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable.

mydir/spam/__init__.py
mydir/spam/module.py
import spam.module
or
from spam import module
做个少女永远怀春 2024-08-30 17:57:14
from file import function_name  ######## Importing specific function
function_name()                 ######## Calling function

import file              ######## Importing whole package
file.function1_name()    ######## Calling function
file.function2_name()    ######## Calling function

是我现在已经理解的两种简单方法,并确保要作为库导入的“file.py”文件仅存在于当前目录中。

from file import function_name  ######## Importing specific function
function_name()                 ######## Calling function

and

import file              ######## Importing whole package
file.function1_name()    ######## Calling function
file.function2_name()    ######## Calling function

Here are the two simple ways I have understood by now and make sure your "file.py" file which you want to import as a library is present in your current directory only.

回眸一笑 2024-08-30 17:57:14

如果定义的函数位于文件 x.py 中:

def greet():
    print('Hello! How are you?')

在要导入该函数的文件中,写入以下内容:

from x import greet

如果您不希望导入文件中的所有函数,这很有用。

If the function defined is in a file x.py:

def greet():
    print('Hello! How are you?')

In the file where you are importing the function, write this:

from x import greet

This is useful if you do not wish to import all the functions in a file.

人心善变 2024-08-30 17:57:14

使用 Python 3.5 或更高版本,您可以使用 importlib.util< /a> 直接将任意位置的 .py 文件作为模块导入,无需修改 sys.path 。

import importlib.util
import sys

def load_module(file_name, module_name)
    spec = importlib.util.spec_from_file_location(module_name, file_name)
    module = importlib.util.module_from_spec(spec)
    sys.modules[module_name] = module
    spec.loader.exec_module(module)
    return module

file_name 参数必须是字符串或类似路径的对象。 module_name 参数是必需的,因为所有加载的 Python 模块都必须有一个(点)模块名称(例如 sysimportlibimportlib .util),但您可以为这个新模块选择任何可用的名称。

您可以这样使用此函数:

my_module = load_module("file.py", "mymod")

使用 load_module() 函数将其导入到 Python 进程后,该模块将可以使用为其指定的模块名称进行导入。

file.py:

print(f"file.py was imported as {__name__}")

one.py:

print(f"one.py was imported as {__name__}")
load_module("file.py", "mymod")
import two

two.py:

print(f"two.py was imported as {__name__})")
import mymod

给定上面的文件,您可以运行以下命令来查看file.py 变得可导入。

$ python3 -m one
one.py was imported as __main__
two.py was imported as two
file.py was imported as mymod

这个答案基于官方Python文档: importlib:直接导入源文件。

Using Python 3.5 or later, you can use importlib.util to directly import a .py file in an arbitrary location as a module without needing to modify sys.path.

import importlib.util
import sys

def load_module(file_name, module_name)
    spec = importlib.util.spec_from_file_location(module_name, file_name)
    module = importlib.util.module_from_spec(spec)
    sys.modules[module_name] = module
    spec.loader.exec_module(module)
    return module

The file_name parameter must be a string or a path-like object. The module_name parameter is required because all loaded Python modules must have a (dotted) module name (like sys, importlib, or importlib.util), but you can choose any available name you want for this new module.

You can use this function like this:

my_module = load_module("file.py", "mymod")

After it has been imported once into the Python process using the load_module() function, the module will be importable using the module name given to it.

file.py:

print(f"file.py was imported as {__name__}")

one.py:

print(f"one.py was imported as {__name__}")
load_module("file.py", "mymod")
import two

two.py:

print(f"two.py was imported as {__name__})")
import mymod

Given the files above, you can run the following command to see how file.py became importable.

$ python3 -m one
one.py was imported as __main__
two.py was imported as two
file.py was imported as mymod

This answer is based on the official Python documentation: importlib: Importing a source file directly.

秋心╮凉 2024-08-30 17:57:14

我想添加这个注释,但我在其他地方不太清楚;在模块/包内,从文件加载时,模块/包名称必须以 mymodule 为前缀。想象一下 mymodule 的布局如下:

/main.py
/mymodule
    /__init__.py
    /somefile.py
    /otherstuff.py

当从 __init__.py 加载 somefile.py/otherstuff.py 时,内容应该看起来像:

from mymodule.somefile import somefunc
from mymodule.otherstuff import otherfunc

I'd like to add this note I don't very clearly elsewhere; inside a module/package, when loading from files, the module/package name must be prefixed with the mymodule. Imagine mymodule being layout like this:

/main.py
/mymodule
    /__init__.py
    /somefile.py
    /otherstuff.py

When loading somefile.py/otherstuff.py from __init__.py the contents should look like:

from mymodule.somefile import somefunc
from mymodule.otherstuff import otherfunc
卖梦商人 2024-08-30 17:57:14
import sys
#print(sys.path)
sys.path.append('../input/tokenization')
import tokenization

要导入任何 .py 文件,您可以使用上面的代码。

首先附加路径,然后导入

注意:'../input/tokenization'目录包含tokenization.py文件

import sys
#print(sys.path)
sys.path.append('../input/tokenization')
import tokenization

To import any .py file, you can use above code.

First append the path and then import

Note:'../input/tokenization' directory contains tokenization.py file

jJeQQOZ5 2024-08-30 17:57:14

导入 .py 文件的最佳方法是通过 __init__.py。最简单的方法是在 .py 文件所在的同一目录中创建一个名为 __init__.py 的空文件。

Mike Grouchy 的这篇 帖子 很好地解释了 __init__.py 及其用于制作、导入和设置 python 包的用途。

the best way to import .py files is by way of __init__.py. the simplest thing to do, is to create an empty file named __init__.py in the same directory that your.py file is located.

this post by Mike Grouchy is a great explanation of __init__.py and its use for making, importing, and setting up python packages.

在风中等你 2024-08-30 17:57:14

我的导入方式是导入文件并使用其名称的简写。

import DoStuff.py as DS
DS.main()

不要忘记您的导入文件必须以 .py 扩展名命名

How I import is import the file and use shorthand of it's name.

import DoStuff.py as DS
DS.main()

Don't forget that your importing file MUST BE named with .py extension

酒浓于脸红 2024-08-30 17:57:14

有几种方法可以包含名称为 abc.py 的 python 脚本,

  1. 例如:如果你的文件名为 abc.py (import abc)
    限制是您的文件应该与调用 python 脚本位于同一位置。

导入abc

  1. 例如如果你的 python 文件位于 Windows 文件夹内。 Windows 文件夹与调用 python 脚本的位置相同。

从文件夹导入 abc

  1. 如果 abc.py 脚本可在文件夹内部的 inside_folder 中使用

从folder.internal_folder导入abc

  1. 正如上面 James 的回答,如果您的文件位于某个固定位置

导入操作系统
导入系统
脚本路径 =“../Test/MyModule.py”
sys.path.append(os.path.abspath(scriptpath))
导入我的模块

如果您的 python 脚本已更新并且您不想上传 - 使用这些语句进行自动刷新。奖金 :)

%load_ext autoreload 
%autoreload 2

There are couple of ways of including your python script with name abc.py

  1. e.g. if your file is called abc.py (import abc)
    Limitation is that your file should be present in the same location where your calling python script is.

import abc

  1. e.g. if your python file is inside the Windows folder. Windows folder is present at the same location where your calling python script is.

from folder import abc

  1. Incase abc.py script is available insider internal_folder which is present inside folder

from folder.internal_folder import abc

  1. As answered by James above, in case your file is at some fixed location

import os
import sys
scriptpath = "../Test/MyModule.py"
sys.path.append(os.path.abspath(scriptpath))
import MyModule

In case your python script gets updated and you don't want to upload - use these statements for auto refresh. Bonus :)

%load_ext autoreload 
%autoreload 2
听风吹 2024-08-30 17:57:14

这帮助我使用 Visual Studio Code 构建我的 Python 项目。

当您未在目录中声明 __init__.py 时,可能会导致此问题。并且该目录成为隐式命名空间包。这是关于 Python 导入和项目结构< /a>.

另外,如果您想使用 Visual Studio Code 运行按钮 运行按钮在顶部栏中,其脚本不在主包内,您可以尝试从实际目录运行控制台。

例如,您想要执行测试包中打开的 test_game_item.py,并且您在 omission (主包)目录中打开了 Visual Studio Code:

├── omission
│   ├── app.py
│   ├── common
│   │   ├── classproperty.py
│   │   ├── constants.py
│   │   ├── game_enums.py
│   │   └── __init__.py
│   ├── game
│   │   ├── content_loader.py
│   │   ├── game_item.py
│   │   ├── game_round.py
│   │   ├── __init__.py
│   │   └── timer.py
│   ├── __init__.py
│   ├── __main__.py
│   ├── resources
│   └── tests
│       ├── __init__.py
│       ├── test_game_item.py
│       ├── test_game_round_settings.py
│       ├── test_scoreboard.py
│       ├── test_settings.py
│       ├── test_test.py
│       └── test_timer.py
├── pylintrc
├── README.md
└── .gitignore

目录结构来自[2]。

您可以尝试设置:

(Windows) Ctrl + Shift + P首选项:打开设置 (JSON)

将此行添加到您的用户设置中:

"python.terminal.executeInFileDir": true

此问题。

This helped me to structure my Python project with Visual Studio Code.

The problem could be caused when you don't declare __init__.py inside the directory. And the directory becomes implicit namespace package. Here is a nice summary about Python imports and project structure.

Also if you want to use the Visual Studio Code run button run buttonin the top bar with a script which is not inside the main package, you may try to run console from the actual directory.

For example, you want to execute an opened test_game_item.py from the tests package and you have Visual Studio Code opened in omission (main package) directory:

├── omission
│   ├── app.py
│   ├── common
│   │   ├── classproperty.py
│   │   ├── constants.py
│   │   ├── game_enums.py
│   │   └── __init__.py
│   ├── game
│   │   ├── content_loader.py
│   │   ├── game_item.py
│   │   ├── game_round.py
│   │   ├── __init__.py
│   │   └── timer.py
│   ├── __init__.py
│   ├── __main__.py
│   ├── resources
│   └── tests
│       ├── __init__.py
│       ├── test_game_item.py
│       ├── test_game_round_settings.py
│       ├── test_scoreboard.py
│       ├── test_settings.py
│       ├── test_test.py
│       └── test_timer.py
├── pylintrc
├── README.md
└── .gitignore

The directory structure is from [2].

You can try set this:

(Windows) Ctrl + Shift + PPreferences: Open Settings (JSON).

Add this line to your user settings:

"python.terminal.executeInFileDir": true

A more comprehensive answer also for other systems is in this question.

苏别ゝ 2024-08-30 17:57:14

如果您要导入的模块不在子目录中,请尝试以下操作并从最深的公共目录运行app.py父目录:

目录结构:

/path/to/common_dir/module/file.py
/path/to/common_dir/application/app.py
/path/to/common_dir/application/subpath/config.json

app.py中,将客户端路径附加到sys.path:

import os, sys, inspect

sys.path.append(os.getcwd())
from module.file import MyClass
instance = MyClass()

可选(如果加载例如配置)(检查似乎是我的用例中最强大的一个)

# Get dirname from inspect module
filename = inspect.getframeinfo(inspect.currentframe()).filename
dirname = os.path.dirname(os.path.abspath(filename))
MY_CONFIG = os.path.join(dirname, "subpath/config.json")

运行

user@host:/path/to/common_dir$ python3 application/app.py

这个解决方案适用于 cli 和 PyCharm。

In case the module you want to import is not in a sub-directory, then try the following and run app.py from the deepest common parent directory:

Directory Structure:

/path/to/common_dir/module/file.py
/path/to/common_dir/application/app.py
/path/to/common_dir/application/subpath/config.json

In app.py, append path of client to sys.path:

import os, sys, inspect

sys.path.append(os.getcwd())
from module.file import MyClass
instance = MyClass()

Optional (If you load e.g. configs) (Inspect seems to be the most robust one for my use cases)

# Get dirname from inspect module
filename = inspect.getframeinfo(inspect.currentframe()).filename
dirname = os.path.dirname(os.path.abspath(filename))
MY_CONFIG = os.path.join(dirname, "subpath/config.json")

Run

user@host:/path/to/common_dir$ python3 application/app.py

This solution works for me in cli, as well as PyCharm.

旧时浪漫 2024-08-30 17:57:14

这就是我从 python 文件调用函数的方法,这对我来说可以灵活地调用任何函数。

import os, importlib, sys

def callfunc(myfile, myfunc, *args):
    pathname, filename = os.path.split(myfile)
    sys.path.append(os.path.abspath(pathname))
    modname = os.path.splitext(filename)[0]
    mymod = importlib.import_module(modname)
    result = getattr(mymod, myfunc)(*args)
    return result

result = callfunc("pathto/myfile.py", "myfunc", arg1, arg2)

This is how I did to call a function from a python file, that is flexible for me to call any functions.

import os, importlib, sys

def callfunc(myfile, myfunc, *args):
    pathname, filename = os.path.split(myfile)
    sys.path.append(os.path.abspath(pathname))
    modname = os.path.splitext(filename)[0]
    mymod = importlib.import_module(modname)
    result = getattr(mymod, myfunc)(*args)
    return result

result = callfunc("pathto/myfile.py", "myfunc", arg1, arg2)
第几種人 2024-08-30 17:57:14

只是为了在另一个 python 文件中导入 python 文件

,假设我有 helper.py python 文件,它具有显示功能,例如,

def display():
    print("I'm working sundar gsv")

现在在 app.py 中,您可以使用显示函数,

import helper
helper.display()

输出,

I'mworking sundar gsv

注意: 无需指定 .py 扩展名。

Just to import python file in another python file

lets say I have helper.py python file which has a display function like,

def display():
    print("I'm working sundar gsv")

Now in app.py, you can use the display function,

import helper
helper.display()

The output,

I'm working sundar gsv

NOTE: No need to specify the .py extension.

-残月青衣踏尘吟 2024-08-30 17:57:14

Python 的一个非常不为人知的功能是能够导入 zip 文件:

library.zip
|-library
|--__init__.py

包的文件 __init__.py 包含以下内容:

def dummy():
    print 'Testing things out...'

我们可以编写另一个可以导入包的脚本来自 zip 存档。只需将 zip 文件添加到 sys.path 即可。

import sys
sys.path.append(r'library.zip')

import library

def run():
    library.dummy()

run()

One very unknown feature of Python is the ability to import zip files:

library.zip
|-library
|--__init__.py

The file __init__.py of the package contains the following:

def dummy():
    print 'Testing things out...'

We can write another script which can import a package from the zip archive. It is only necessary to add the zip file to the sys.path.

import sys
sys.path.append(r'library.zip')

import library

def run():
    library.dummy()

run()
与酒说心事 2024-08-30 17:57:14

这可能听起来很疯狂,但如果您只是为其创建包装脚本,则可以创建指向要导入的文件的符号链接。

This may sound crazy but you can just create a symbolic link to the file you want to import if you're just creating a wrapper script to it.

没有心的人 2024-08-30 17:57:14

您还可以执行以下操作:from filename import Something

示例:from client import Client
请注意,您不需要 .py .pyw .pyui 扩展名。

You can also do this: from filename import something

example: from client import Client
Note that you do not need the .py .pyw .pyui extension.

网名女生简单气质 2024-08-30 17:57:14

如上所述,有很多方法,但我发现我只想导入文件的内容,并且不想必须编写行和行并且必须导入其他模块。因此,我想出了一种获取文件内容的方法,即使使用点语法 (file.property),而不是将导入的文件与您的文件合并。

首先,这是我要导入的文件,data.py

    testString= "A string literal to import and test with"

注意:您可以使用 .txt 扩展名反而。

mainfile.py 中,首先打开并获取内容。

    #!usr/bin/env python3
    Data=open('data.txt','r+').read()

现在您已将内容作为字符串,但尝试访问 data.testString 将导致错误,因为 datastr 的实例类,即使它确实有一个属性 testString ,它也不会执行您期望的操作。
接下来,创建一个类。例如(双关语),ImportedFile

    class ImportedFile:

并将其放入其中(使用适当的缩进):

    exec(data)

最后,像这样重新分配data

    data=ImportedFile()

就是这样!只需像访问任何其他模块一样进行访问,输入 print(data.testString) 将在控制台上打印用于导入和测试的字符串文字

但是,如果您想要 from mod import * 的等价物,只需删除类、实例分配,然后取消 exec 的缩进即可。

希望这有帮助:)
-本吉

There are many ways, as listed above, but I find that I just want to import he contents of a file, and don't want to have to write lines and lines and have to import other modules. So, I came up with a way to get the contents of a file, even with the dot syntax (file.property) as opposed to merging the imported file with yours.

First of all, here is my file which I'll import, data.py

    testString= "A string literal to import and test with"

Note: You could use the .txt extension instead.

In mainfile.py, start by opening and getting the contents.

    #!usr/bin/env python3
    Data=open('data.txt','r+').read()

Now you have the contents as a string, but trying to access data.testString will cause an error, as data is an instance of the str class, and even if it does have a property testString it will not do what you expected.
Next, create a class. For instance (pun intended), ImportedFile

    class ImportedFile:

And put this into it (with the appropriate indentation):

    exec(data)

And finally, re-assign data like so:

    data=ImportedFile()

And that's it! Just access like you would for any-other module, typing print(data.testString) will print to the console A string literal to import and test with.

If, however, you want the equivalent of from mod import * just drop the class, instance assignment, and de-dent the exec.

Hope this helps:)
-Benji

我不在是我 2024-08-30 17:57:14
from y import * 
  • 假设您有文件 x 和 y。
  • 您想将 y 文件导入到 x。

然后转到您的 x 文件并放置上述命令。要测试这一点,只需在 y 文件中添加一个打印函数,当导入成功后,它应该在 x 文件中打印它。

from y import * 
  • Say you have a file x and y.
  • You want to import y file to x.

then go to your x file and place the above command. To test this just put a print function in your y file and when your import was successful then in x file it should print it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文