Reputation: 77
When creating Python script on Jupyter, is it possible to call a function from another Python file?
When I try to call, it works on Terminal but does not work on Jupyter.
Upvotes: 4
Views: 12789
Reputation: 3820
For example, suppose I have a Person.py
file and it is in the working directory of my current jupyter notebook. Furthermore, suppose it is simple and here it is
def get_rss(y, x):
x = sm.add_constant(x)
results=sm.OLS(y, x).fit()
rss= (results.resid**2).sum()
N=results.nobs
K=results.df_model
return rss, N, K, results
def myfunc(d):
print("Hello my name is " + d)
When I try to call, it works on Terminal but does not work on Jupyter.
When I try to call it as import Person
, it works on Jupyter cell but I can not access the functions inside of it.
For example, if you tried writing this in Jupyter Notebook you might get this message after typing this Person.myfunc('ds')
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-60-63fdc0f35859> in <module>
----> 1 Person.myfunc('ds')
AttributeError: module 'Person' has no attribute 'myfunc'
Restart your kernel and this should eliminate this problem. I hope this clarifies your question as well could be considered as an answer.
Upvotes: 3
Reputation: 317
Firstly, if you're already working with other files, I recommend that you stop using jupyter and even terminal aswell.
You can use Pycharm instead.
If you were just learning, you could use jupyter but if you're already at that stage I recommend you to stick to Pycharm.
Pycharm is a nice IDE, where you can run the files directly on it, and has a lot more cool features.
Also, to use it in jupyter, just import the files you want:
import #whatever file you want
Upvotes: 0