your programing

다른 Python 파일을 가져 오는 방법은 무엇입니까?

lovepro 2020. 9. 30. 11:13
반응형

다른 Python 파일을 가져 오는 방법은 무엇입니까?


Python에서 다른 파일을 어떻게 가져 옵니까?

  1. 특정 파이썬 파일을 정확히 어떻게 가져올 수 import file.py있습니까?
  2. 특정 파일 대신 폴더를 가져 오려면 어떻게해야합니까?
  3. 사용자 입력을 기반으로 런타임에 Python 파일을 동적으로로드하고 싶습니다.
  4. 파일에서 특정 부분 하나만로드하는 방법을 알고 싶습니다.

예를 들어 다음과 main.py같습니다.

from extra import * 

이것은 나에게 모든 정의를 제공하지만 extra.py아마도 내가 원하는 것은 단일 정의 일 것입니다.

def gap():
    print
    print

나는 어떻게 추가합니까 import단지 수에 문 gap에서 extra.py?


importlib모듈을 프로그래밍 방식으로 가져 오기 위해 Python에 최근 추가되었습니다. https://docs.python.org/3/library/importlib.html#module-importlib__import__참조 하십시오.

import importlib

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

업데이트 : 아래 답변은 오래되었습니다 . 위의 최신 대안을 사용하십시오.

  1. 그냥 import file'평'확장자없이.

  2. 라는 빈 파일을 추가하여 폴더를 패키지로 표시 할 수 있습니다 __init__.py.

  3. __import__기능을 사용할 수 있습니다 . 모듈 이름을 문자열로받습니다. (다시 말하지만 '.py'확장자가없는 모듈 이름입니다.)

    pmName = input('Enter module name:')
    pm = __import__(pmName)
    print(dir(pm))
    

    help(__import__)자세한 내용을 보려면 입력 하십시오.


장단점이있는 파이썬 파일을 가져 오는 방법에는 여러 가지가 있습니다.

자신에게 적합한 첫 번째 가져 오기 전략을 서둘러 선택하지 마십시오. 그렇지 않으면 나중에 코드베이스가 필요에 맞지 않을 때 다시 작성해야합니다.

가장 쉬운 예제 # 1부터 설명하고 가장 전문적이고 강력한 예제 # 7로 이동하겠습니다.

예제 1, 파이썬 인터프리터로 파이썬 모듈 가져 오기 :

  1. 이것을 /home/el/foo/fox.py에 넣으십시오.

    def what_does_the_fox_say():
      print("vixens cry")
    
  2. 파이썬 인터프리터에 들어가십시오.

    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
    >>> 
    

    파이썬 인터프리터를 통해 fox를 가져 what_does_the_fox_say()오고 fox.py 내 에서 파이썬 함수 호출했습니다.

예제 2, 스크립트 에서execfile 또는 ( execPython 3 )를 사용 하여 다른 Python 파일을 제자리에서 실행합니다.

  1. 이것을 /home/el/foo2/mylib.py에 넣으십시오.

    def moobar():
      print("hi")
    
  2. 이것을 /home/el/foo2/main.py에 넣으십시오.

    execfile("/home/el/foo2/mylib.py")
    moobar()
    
  3. 파일을 실행하십시오.

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

    moobar 함수는 mylib.py에서 가져 와서 main.py에서 사용할 수있게되었습니다.

예 3, ...에서 가져 오기 ... 기능 사용 :

  1. 이것을 /home/el/foo3/chekov.py에 넣으십시오.

    def question():
      print "where are the nuclear wessels?"
    
  2. 이것을 /home/el/foo3/main.py에 넣으십시오.

    from chekov import question
    question()
    
  3. 다음과 같이 실행하십시오.

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

    chekov.py에 다른 함수를 정의했다면, import *

예 4, 가져온 위치와 다른 파일 위치에있는 경우 riaa.py 가져 오기

  1. 이것을 /home/el/foo4/stuff/riaa.py에 넣으십시오.

    def watchout():
      print "computers are transforming into a noose and a yoke for humans"
    
  2. 이것을 /home/el/foo4/main.py에 넣으십시오.

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

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

    다른 디렉토리에서 외부 파일의 모든 것을 가져옵니다.

예제 5, 사용 os.system("python yourfile.py")

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

예제 6, python startuphook을 피기 백하여 파일을 가져옵니다.

업데이트 : 이 예제는 python2와 3 모두에서 작동했지만 이제는 python2에서만 작동합니다. python3은 저 숙련 파이썬 라이브러리 작성자가 남용했기 때문에이 사용자 시작 후크 기능 세트를 제거하여 모든 사용자 정의 프로그램보다 먼저 전역 네임 스페이스에 코드를 비공식적으로 주입했습니다. 이것이 python3에서 작동하기를 원한다면 더 창의적이어야합니다. 방법을 알려 주면 파이썬 개발자가 해당 기능 세트도 비활성화하므로 혼자서 할 수 있습니다.

참조 : https://docs.python.org/2/library/user.html

이 코드를 홈 디렉토리에 넣으십시오. ~/.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을 사용하고 있음을 의미하며 기본적으로 시작 후크가 비활성화되어 있습니다.

이 jist에 대한 크레딧은 https://github.com/docwhat/homedir-examples/blob/master/python-commandline/.pythonrc.py로 이동합니다.

예제 7, 가장 강력한 : bare import 명령을 사용하여 Python에서 파일 가져 오기 :

  1. 새 디렉토리 만들기 /home/el/foo5/
  2. 새 디렉토리 만들기 /home/el/foo5/herp
  3. __init__.pyherp 아래에 이름이 비어있는 파일을 만듭니다 .

    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.pyPut this in there 라는 새 파일을 만듭니다 .

    def skycake():
      print "SkyCake evolves to stay just beyond the cognitive reach of " +
      "the bulk of men. SKYCAKE!!"
    
  7. 진실의 순간, Make the new file /home/el/foo5/main.py, 이것을 거기에 넣으 십시오 .

    from herp.derp.yolo import skycake
    skycake()
    
  8. 실행 :

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

    __init__.py파일은 개발자가이 디렉토리를 가져 오기 가능한 패키지로 의도한다는 것을 Python 인터프리터에 전달합니다.

디렉토리 아래에 모든 .py 파일을 포함하는 방법에 대한 내 게시물을 보려면 여기를 참조하십시오 : https://stackoverflow.com/a/20753073/445131


알려진 이름으로 '런타임'에 특정 Python 파일을 가져 오려면 다음을 수행하십시오.

import os
import sys

...

scriptpath = "../Test/MyModule.py"

# 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

한 폴더에서 다른 폴더로 파이썬 파일을 가져 오는 복잡한 방법이 많지 않습니다. __init__.py 파일을 생성 하여이 폴더가 python 패키지임을 선언 한 다음 가져 오려는 호스트 파일로 이동하십시오.

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


문서 가져 오기 ..- 참조 용 링크

__init__.py파일은 파이썬이 디렉토리를 패키지를 포함하는 것으로 취급하도록하는 데 필요합니다. 이것은 문자열과 같은 공통 이름을 가진 디렉토리가 나중에 모듈 검색 경로에서 발생하는 유효한 모듈을 의도하지 않게 숨기는 것을 방지하기 위해 수행됩니다.

__init__.py빈 파일 일 수도 있지만 패키지에 대한 초기화 코드를 실행하거나 __all__변수를 설정할 수도 있습니다.

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

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"파일이 현재 디렉토리에만 있는지 확인하십시오.


.py 파일을 가져 오는 가장 좋은 방법은 __init__.py. 가장 간단한 방법 __init__.py은 your.py 파일이있는 디렉토리에 이름이 지정된 빈 파일을 만드는 것입니다.

Mike Grouchy 의이 게시물__init__.py파이썬 패키지를 만들고, 가져오고, 설정 하는 데 대한 훌륭한 설명 과 사용법입니다.


첫 번째 경우 : file 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

그러면 파일에 A.py있는 파일 의 모든 기능을 사용할 수 있습니다.B.py


두 번째 경우 : file folder/A.py에서 파일 을 가져 오려고합니다 B.py.이 두 파일은 다음과 같이 동일한 폴더에 없습니다.

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

파일 B에서이 작업을 수행 할 수 있습니다.

import folder.A

또는

from folder.A import *

또는

from folder.A import THINGS_YOU_WANT_TO_IMPORT_IN_A

그러면 파일에 A.py있는 파일 의 모든 기능을 사용할 수 있습니다.B.py


요약 : 첫 번째 경우 file A.py은 file B.py에서 가져 오는 모듈이며 구문을 사용했습니다 import module_name. 두 번째 경우 folder는 모듈을 포함하는 패키지이며 A.py구문을 사용했습니다 import package_name.module_name.

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


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


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

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.


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.


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.


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.


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

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


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.


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)

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()

참고URL : https://stackoverflow.com/questions/2349991/how-to-import-other-python-files

반응형