简体   繁体   English

将输入参数从 jupyter notebook 传递给脚本

[英]Pass input parameters to script from jupyter notebook

I am trying to run a python script provided by a file from a Jupyter notebook.我正在尝试运行由 Jupyter 笔记本中的文件提供的 python 脚本。 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

Values can be passed through to the shell command using the {} notation.可以使用{}表示法将值传递给 shell 命令。 See this link for additional handling between the Python runtime and shell commands.有关 Python 运行时和 shell 命令之间的其他处理,请参阅链接。

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.显然,可以删除echo以使其实际调用python命令,这就是原始问题所追求的。

Would it be OK to use the subprocess package?使用 subprocess 包可以吗? 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))

Use the $ sign to access Python variables.使用$符号访问 Python 变量。

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

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

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM