5

I am trying to run a python script provided by a file from a Jupyter notebook. The script is running if I use the following command:

!python script.py --input_path /folder/input --output_path /folder/output/

But I need to pass those paths from a variable of my notebook. How can I do it?

Tried this but it didn't work:

input = "/folder/input"
output = "/folder/output/"

!python script.py --input_path input --output_path output
1
  • You should ideally import script, then call it rather than using Jupyter to run a shell command Commented Oct 9, 2020 at 20:49

3 Answers 3

5
+50

Values can be passed through to the shell command using the {} notation. See this link for additional handling between the Python runtime and shell commands.

For example:

input = "/folder/input"
output = "/folder/output/"

!echo python script.py --input_path "{input}" --output_path "{output}"

Prints the following output:

python script.py --input_path "/folder/input" --output_path "/folder/output/"

Obviously, the echo can be removed to make it actually invoke the python command, which is what the original question is after.

Sign up to request clarification or add additional context in comments.

Comments

2

Use the $ sign to access Python variables.

input = "/folder/input"
output = "/folder/output/"

!python script.py --input_path $input --output_path $output

Comments

2

Would it be OK to use the subprocess package? Here I am running a script in the same folder as the notebook. It works well.

import subprocess
input_file = '/folder/input'
output_file = '/folder/output'
subprocess.run('python script.py --input_path {} --output_path {}'.format(input_file, output_file))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.