[英]Running a python program from jupyter notebook while passing filenames as arguments
[英]Running python scripts with variable parser arguments from Jupyter Notebook
我正在研究變壓器。
我在那里有一個 python 腳本,它通過 argparse 將參數作為輸入。
這是其中的一部分:
parser = argparse.ArgumentParser()
parser.add_argument("--model_type", default=None, type=str, required=True,
help="Model type selected in the list: " + ", ".join(MODEL_CLASSES.keys()))
parser.add_argument("--model_name_or_path", default=None, type=str, required=True,
help="Path to pre-trained model or shortcut name selected in the list: " + ", ".join(ALL_MODELS))
我希望能夠使用不同的參數迭代調用腳本。 我可以使用 %run 或 !python < bash command > 調用腳本,但是我不能將變量傳遞給它以解釋為參數,因為它將變量視為實際的字符串值:
%run examples/run_lm_finetuning.py --gradient_accumulation_steps=1 --output_dir='output_medium' --model_type='gpt2' \
--model_name_or_path=model_load --do_train --train_data_file='/root/sharedfolder/omri/data/pieces/backup/{}'.format(file)\
--overwrite_output_dir --per_gpu_train_batch_size=1 --per_gpu_eval_batch_size=1 --save_total_limit=5
返回:
OSError: Model name 'model_load' was not found in
model name list (gpt2, gpt2-medium, gpt2-large, gpt2-xl, distilgpt2).
We assumed 'model_load' was a path or url to a configuration file named
config.json or a directory containing such a file but couldn't find any
such file at this path or url.
看起來{}
擴展了變量。 我偶然發現它嘗試執行 Python f''
格式。 我在%run
docs 中沒有看到它; 它必須是 %magic 語法的一部分。
無論如何,使用一個簡單的echo
腳本:
In [29]: cat echo.py
import sys
print(sys.argv)
In [30]: foo = "a string"
In [31]: run echo.py {foo} bar
['echo.py', 'a', 'string', 'bar']
In [32]: run echo.py "{foo}" bar
['echo.py', 'a string', 'bar']
===
用另一種魔法
In [71]: astr="*.h5"
In [72]: ls {astr}
abc_copy.h5 string.h5 testdate.h5 test_str.h5...
===
$
也這樣做:
In [79]: foo = "a string"
In [80]: run echo.py $foo bar
['echo.py', 'a', 'string', 'bar']
IPython.core.magic.no_var_expand(magic_func) 將魔法函數標記為不需要變量擴展
默認情況下,IPython 將傳遞給 magics 的行中的 {a} 或 $a 解釋為變量,這些變量應該在將行傳遞給 magic 函數之前從交互式命名空間內插。 這並不總是可取的,例如當魔法執行 Python 代碼時(%timeit、%time 等)。 使用 @no_var_expand 裝飾魔法以選擇退出變量擴展。
https://ipython.readthedocs.io/en/stable/api/generated/IPython.core.magic.html
RafalS 的回答很棒,但如果您願意,不會打印標准輸出,方法如下:
將整個語句放在 fstring 中並分配給變量run :
run = f"python examples/run_lm_finetuning.py\
--model_name_or_path={model_load}\
--train_data_file='/root/sharedfolder/omri/data/pieces/backup/{file}'\
--overwrite_output_dir\
--per_gpu_train_batch_size=1\
--per_gpu_eval_batch_size=1\
--save_total_limit=5"
然后通過簡單的方式運行 Jupyter shell:
!{run}
那么%run
model_load
應該被解釋為 python 變量嗎? 那會有點奇怪,你不覺得嗎? 嘗試直接從 python 調用 python,而不是通過 ipython 魔術函數:
In [18]: import subprocess
In [19]: model_load = "gpt2"
In [20]: subprocess.run(f"python file.py --model_name_or_path={model_load}", shell=True)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.