简体   繁体   English

如何评估将在Jupyter Notebook中执行的python脚本的路径

[英]How to evaluate the path to a python script to be executed within Jupyter Notebook

Note: I am not simply asking how to execute a Python script within Jupyter, but how to evaluate a python variable which would then result in the full path of the Python script I was to execute. 注意:我不是简单地问如何在Jupyter中执行Python脚本,而是要如何求一个python变量的值,这将导致我要执行的Python脚本的完整路径。

In my particular scenario, some previous cell on my notebook generates a path based on some condition. 在我的特定情况下,笔记本上的某些先前单元会根据某种条件生成一条路径。

Example on two possible cases: 两种可能情况的示例:

  1. script_path = /project_A/load.py
  2. script_path = /project_B/load.py

Then some time later, I have a cell where I just want to execute the script. 然后过了一段时间,我有了一个只想执行脚本的单元。 Usually, I would just do: %run -i /project_A/load.py 通常,我会这样做: %run -i /project_A/load.py

but I want to keep the cell's code generic by doing something like: 但我想通过执行以下操作来保持单元的代码通用:

%run -i script_path

where script_path is a Python variable whose value is based on the conditions that are evaluated earlier in my Jupyter notebook. 其中script_path是一个Python变量,其值基于Jupyter笔记本中先前评估的条件。

The above would not work because Jupyter would then complain that it cannot find script_path.py . 上面的方法不起作用,因为Jupyter会抱怨说找不到script_path.py

Any clues how I can have a Python variable passed to the %run magic? 有什么线索可以将Python变量传递给%run魔术吗?

One hacky way would be to change the directory via %cd path 一种变通的方法是通过%cd path更改目录

and then run the script with %run -i file.py 然后使用%run -i file.py运行脚本

E: I know that this is not exactly what you were asking but maybe it helps with your problem. E:我知道这并不是您要问的,但也许可以解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Jupyter Notebook中的输入运行python脚本 - Running a python script with inputs from within Jupyter Notebook 使用特定的virtualenv在Jupyter笔记本中执行Python脚本 - Execute Python script within Jupyter notebook using a specific virtualenv 从python脚本中启动jupyter笔记本进行调试 - Starting jupyter notebook from within python script for debugging Python Jupyter Notebook 内的多处理 - Python Multiprocessing within Jupyter Notebook 如何使通过Jupyter.kernel.execute命令执行的python命令在Jupyter Notebook的输入单元格中可见 - How to make a python command executed via Jupyter.kernel.execute command visible in an Input Cell in Jupyter Notebook 如何检查 Python 模块是否正在导入 Jupyter Notebook - How to check if a Python module is being imported within a Jupyter Notebook Jupyter Notebook,Python:如何在函数内调用魔法? - Jupyter Notebook, Python: How to call a magic from within a function? 如何在Python包内的Jupyter Notebook中显示.gif - How to display a .gif in a Jupyter Notebook within a Python package 如何从Jupyter Notebook中的Python字符串执行bash脚本? - How to execute a bash script from a Python string in Jupyter Notebook? 如何在 jupyter notebook 上将 python 脚本保存为 .py 文件 - How to save python script as .py file on jupyter notebook
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM