gpt4 book ai didi

python - 函数中的 Jupyter shell 命令

转载 作者:行者123 更新时间:2023-12-05 03:34:47 25 4
gpt4 key购买 nike

我正在尝试创建一个函数,以使用 shell 命令在 jupyter notebook 中加载 Sagemaker 模型。当我尝试将函数存储在 utilities.py 文件中并将其用于多个笔记本时,问题就出现了。

这是我在 jupyter 实验室笔记本中获取的 utilities.py 文件的内容。

def get_aws_sagemaker_model(model_loc):
"""
TO BE USED IN A JUPYTER NOTEBOOK

extracts a sagemaker model that has ran and been completed

deletes the copied items and leaves you with the model

note that you will need to have the package installed with correct
versioning for whatever model you have trained
ie. if you are loading an XGBoost model, have XGBoost installed

Args:
model_loc (str) : s3 location of the model including file name

Return:
model: unpacked and loaded model
"""

import re
import tarfile
import os
import pickle as pkl

# extract the filename from beyond the last backslash
packed_model_name = re.search("(.*\/)(.*)$" , model_loc)[2]

# copy and paste model file locally
command_string = "!aws s3 cp {model_loc} ."
exec(command_string)

# use tarfile to extract
tar = tarfile.open(packed_model_name)

# extract filename from tarfile
unpacked_model_name = tar.getnames()[0]

tar.extractall()
tar.close()

model = pkl.load(open(unpacked_model_name, 'rb'))

# cleanup copied files and unpacked model
os.remove(packed_model_name)
os.remove(unpacked_model_name)

return model

尝试执行命令字符串时出现错误:

Traceback (most recent call last):

File "/home/ec2-user/anaconda3/envs/env/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3444, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)

File "/tmp/ipykernel_10889/996524724.py", line 1, in <module>
model = get_aws_sagemaker_model("my-model-loc")

File "/home/ec2-user/SageMaker/env/src/utilities/model_helper_functions.py", line 167, in get_aws_sagemaker_model
exec(command_string)

File "<string>", line 1
!aws s3 cp my-model-loc .
^
SyntaxError: invalid syntax

exec 检查语法之前,jupyter 似乎没有收到命令。除了将函数复制到我使用的每个 jupyter notebook 之外,还有其他解决方法吗?

谢谢!

最佳答案

您可以使用 IPython 外壳的 transform_cell 方法将 IPython 语法转换为有效的纯 Python 语法:

from IPython import get_ipython
ipython = get_ipython()

code = ipython.transform_cell('!ls')
print(code)

将显示:

get_ipython().system('!ls')

您可以将其用作 exec 的输入:

exec(code)

或者直接:

exec(ipython.transform_cell('!ls'))

关于python - 函数中的 Jupyter shell 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70068720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com