简体   繁体   中英

Using a .py file inside a .py file

I'm fairly new to python and I've been exclusively using Jupyter Notebooks. When I need to run a .py file I have saved somewhere in my computer what I normally do is just use the magic command %run

%run '/home/cody/.../Chapter 3/efld.py'
%run '/home/cody/.../Chapter 5/tan_vec.py'

Then in the next cell I can run efld.py without a problem. But tan_vec.py uses efld.py and looks like this,

def tan_vec(r):
    import numpy as np
    #Finds the tangent vector to the electric field at point 'r'
    e = efld(r)
    e = np.array(e) #Turn 'e' into a numpy array so I can do math with it a little easier.
    emag = np.sqrt(sum(e**2)) #Magnitude of the 
    return e / emag

when I try to run that I get the error;

"NameError: name 'efld' is not defined."

I tried most of the things here but none of them seamed to work.

Am I going about running py files in the notebook wrong? Is there a better way to run/call py files in a notebook? How do make it so that I can run one py file inside another py file?

EDIT

Thank you everyone for your help! I just wanted to add the final code that worked in case anyone comes across this later and wants to see what i did.

def tan_vec(r):
    #import sys
    #sys.path.insert(0, '/home/cody/Physics 331/Textbook Programs/Chapter 3')
    from efld import efld 
    import numpy as np
    #Finds the tangent vector to the electric field at point 'r'
    e = efld(r)
    e = np.array(e) #Turn 'e' into a numpy array so I can do math with it a little easier.
    emag = np.sqrt(sum(e**2)) #Magnitude of the 
    return e / emag

The first two lines are commented out because they were only needed if efld.py and tan_vec.py are saved in different folders. I just added a copy of efld to the same folder and tan_vec and I didn't need them any more.

Thank you again for all the help!

put the files in the jupyter root directory. then just import those files (now called modules) at the top of your first cell:

from efld import *
from tan_vec import *

If one requires the other, put the import on top inside the respective file rather than to jupyter.

Given that those modules don't throw any exceptions within itself, you can then call all functions in it in all other cells.

e = efld(r)

Pay attention that all functions within both files are named differently.


Edit : As pointed out in the comments below, you can also import your functions directly:

from efld import efld as <whatever>

In this way, you can rename your functions to <whatever> and don't have to rename the ones with identical names, sitting in different modules/files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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