0

I have a python script located inside a hidden folder due to security reasons inside a Jupyter Notebook environment (JupyterHub/JupyterLab). However I want to execute it from the notebook cell.

I have come across this post How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook?

And tried the same with the magic function

%run -i 'script.py'

But it says No file or directory found. Is there a way to execute a hidden python file from the code cell?

Ranji Raj
  • 778
  • 4
  • 18

1 Answers1

1

You still need to use the path to the file.
Assuming the hiding is the only security measure, you can still use %run. Let's suppose your script my_script.py is in a hidden directory named hidden_dir that occurs in the same directory as your notebook file. This is your command:

%run './.hidden_dir/my_script.py'

Remember, when working out the path for your %run statement, you can always use ls in cells in the notebook to test and see what it can actually see and access. In this case, running the following in a cell in the notebook should list the script my_script.py:

ls .hidden_dir -lah

You'd just use ls -lah in a notebook cell in the first place to see the directories, including hidden ones. Compare the results of that to what you see with ls -lh because with ls -lh the hidden directories won't be shown without the -a option.

Note, unless you want to run the script in the notebook namespace, it is just %run 'path/to/script/<name_of_script>'. You didn't say if you needed that option or not, and so I left it out in my example to further simplify. Add in the -i option if you are setting some options in the notebook or want objects created in the script accessible in the notebook after running.

Related to sorting out the path, there's a common 'gotcha' involved with using cd in a cell. If you need to change the working directory within the namespace of the notebook itself, you use the %cd magic (documented here), and not !cd or equivalent. !cd or equivalent only changes the directory off in the shell instance that gets triggered by the exclamation point. Once that line of code is done, the temporary shell is gone, and so you've done nothing to the notebook. You can always check the current working directory in the notebook by running the following in a notebook cell:

pwd

Together, ls (and the variant ls -lah), %cd, & pwd let you explore what the Jupyter notebook has access to and work out paths for use in Python and shell commands in the Jupyter notebook.

Wayne
  • 6,607
  • 8
  • 36
  • 93