Import own .py files in anaconda spyder

后端 未结 5 1635
梦毁少年i
梦毁少年i 2021-02-14 16:21

I\'ve written my own mail.py module in spider (anaconda). I want to import this py file in other python (spider) files just by \'import mail\'

I searched on the internet

相关标签:
5条回答
  • 2021-02-14 16:38

    I had the same problem, my files were in same folder, yet it was throwing an error while importing the "to_be_imported_file.py".

    I had to run the "to_be_imported_file.py" seperately before importing it to another file.

    I hope it works for you too.

    0 讨论(0)
  • 2021-02-14 16:41

    To import any python script, it should exist in the PYTHONPATH. You can check this with the following code:

    import sys
    print sys.path
    

    To import your Python script:

    1. Put both the scripts (main and the imported python script) in the same directory.
    2. Add the location of the file to be imported to the sys.path.

    For example, if the script is located as '/location/to/file/script.py':

     import sys
     sys.path.append('/location/to/file/')
     import script
    
    0 讨论(0)
  • 2021-02-14 16:46

    when calling any function from another file, it should be noted to not import any library inside the function

    0 讨论(0)
  • 2021-02-14 16:48

    There are many options, e.g.

    • Place the mail.py file alongside the other python files (this works because the current working dir is on the PYTHONPATH.
    • Save a copy of mail.py in the anaconda python environment's "/lib/site-packages" folder so it will be available for any python script using that environment.
    0 讨论(0)
  • 2021-02-14 16:56

    I did a slightly different solution approach that is less sophisticated. When I start my anaconda terminal it is at a C prompt. I just did a cd d:\mypython\lib in the beginning window before starting python. once I did that I could simply just import my own classes that I put in that library with "import MyClass as my" then I was off and running. It is interesting, I did 2 days of internet searching in my part time and could not find the answer either, until I asked a friend.

    cd d:\mypython\lib
    python
    >>> import MyClass as my
    >>> my1=my.MyClass()
    >>> my1.doSomething() 
    

    worked for me on my anaconda / windows 10 environment python 3.6.6.

    0 讨论(0)
提交回复
热议问题