我有个问题。我想在我的朱庇特笔记本中调用Python文件。我查看了How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook?,但不幸的是,%run -i 'file.py'和!python file.py无法工作,因为我的文件与朱庇特笔记本文件不在同一个文件夹中。
那么,我如何从不同的文件夹调用Python文件呢?Jupyter笔记本
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 directoryfile.py
def main():
print("Hello")
return "test"
if __name__ == "__main__":
main()发布于 2022-04-05 09:11:29
chdir()将当前工作目录更改为给定路径。
这应该是你的工作:
import os
filepath = r'C:\Users\user\OneDrive - user\folder'
os.chdir(filepath)
%run file.py发布于 2022-04-19 21:33:09
假设您的文件位于子文件夹./playground/test folder中,那么您可以这样做:
file_name = ".\\playground\\test folder\\hello_world.py"
%run "$file_name"诀窍是在使用%run时,在文件名(如果路径包含空格)周围使用引号。
如果您使用!python,则同样适用
file_name = ".\\playground\\test folder\\hello_world.py"
!python "$file_name"https://stackoverflow.com/questions/71748649
复制相似问题