'Call Python file with main method inside Jupyter notebook
I have a problem. I want to call inside my Jupyter Notebook a Python File. I looked at How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook? but unfortunately %run -i 'file.py' and !python file.py does not work, because my file is not in the same folder as the Jupyter Notebook file.
So how could I call a Python file from a different folder? Jupyter Notebook
from pathlib import *
# I am using pathlib, because of the whitespace in OneDrive
p = Path('C://Users//user//OneDrive - user//folder//file.py')
# %run -i ''C://Users//user//OneDrive - user//folder//file.py'
!python p
[OUT] python: can't open file 'C:\Users\user\Documents\p': [Errno 2] No such file or directory
file.py
def main():
print("Hello")
return "test"
if __name__ == "__main__":
main()
Solution 1:[1]
chdir() changes the current working directory to the given path.
This should do your work:
import os
filepath = r'C:\Users\user\OneDrive - user\folder'
os.chdir(filepath)
%run file.py
Solution 2:[2]
Assuming your file is in a sub-folder ./playground/test folder, then you could do this:
file_name = ".\\playground\\test folder\\hello_world.py"
%run "$file_name"
The trick is to use quotation marks around the file name (if path contains spaces) when using %run.
The same applies if you use !python:
file_name = ".\\playground\\test folder\\hello_world.py"
!python "$file_name"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | SM1312 |
| Solution 2 |
