如何从ipython shell命令get_ipython().system.raw()获取'stdout'?
我正在开发一个模块,从如何从ipython shell命令get_ipython().system.raw()获取'stdout'?,ipython,jupyter-notebook,gsutil,google-colaboratory,Ipython,Jupyter Notebook,Gsutil,Google Colaboratory,我正在开发一个模块,从colaboratory(请参阅:)将tensorflow中的保存/恢复检查点添加到google云存储。我的代码使用ipythonmagic和shell命令从笔记本外壳运行。但是我发现您无法从python模块导入这些方法(dooh!),所以现在我正在尝试转换为python本机 如何从'get_ipython().system.raw()获取stdout? 我希望得到与以下值相同的值: # ipython shell command !gsutil ls $bucket_pa
colaboratory
(请参阅:)将tensorflow中的保存/恢复检查点添加到google云存储。我的代码使用ipython
magic和shell命令从笔记本外壳运行。但是我发现您无法从python模块导入这些方法(dooh!),所以现在我正在尝试转换为python本机
如何从'get_ipython().system.raw()获取stdout
?
我希望得到与以下值相同的值:
# ipython shell command
!gsutil ls $bucket_path
我试图使用get\u ipython().system\u raw()
,但我没有从stdout
中获取值
bucket = "my-bucket"
bucket_path = "gs://{}/".format(bucket)
retval = get_ipython().system_raw("gsutil ls {}".format(bucket_path))
print(bucket_path, gsutil_ls)
# BUG: get_ipython().system_raw) returns None
# retval != !gsutil ls $bucket_path
if "BucketNotFoundException" in gsutil_ls[0]:
raise ValueError("ERROR: GCS bucket not found, path={}".format(bucket_path))
# retval == None
有更好的方法吗
[已解决]
根据下面的答案,这里有一个更好的方法:
from google.cloud import storage
def gsutil_ls(bucket_name, project_id):
client = storage.Client( project=project_id )
bucket_path = "gs://{}/".format(bucket_name)
bucket = client.get_bucket(bucket_name)
files = ["{}{}".format(bucket_path,f.name) for f in bucket.list_blobs() ]
# print(files)
return files
bucket_name = "my-bucket"
gsutil_ls(bucket_name, "my-project")
# same as `!gsutil ls "gs://{}/".format(bucket_name) -p "my-project"`
我建议使用googlecloudpython。这些库用于与Google云平台服务交互,它们是用一组不同的编码语言编写的。您可以在中找到云存储客户端库的详细文档,但我也为您编写了一个小样本代码,它返回的内容与您尝试使用的
gsutil ls
命令中的内容相同
from google.cloud import storage
client = storage.Client()
bucket_name = "<YOUR_BUCKET_NAME>"
bucket_path = "gs://{}/".format(bucket_name)
bucket = client.get_bucket(bucket_name)
blobs = list(bucket.list_blobs())
for blob in blobs:
print("{}{}".format(bucket_path,blob.name))
从google.cloud导入存储
client=storage.client()
bucket_name=“”
bucket_path=“gs://{}/”。格式(bucket_名称)
bucket=client.get\u bucket(bucket\u名称)
blobs=list(bucket.list\u blobs())
对于blob中的blob:
打印(“{}{}.format(bucket_path,blob.name))
运行此代码的输出如下所示:
gs://<YOUR_BUCKET_NAME>/file_1.png
gs://<YOUR_BUCKET_NAME>/file_2.png
gs://<YOUR_BUCKET_NAME>/file_3.png
gs:///file_1.png
gs:///文件_2.png
gs:///文件_3.png
这与运行gsutil ls
的结果相同,因此您可以从这一点开始开发。在任何情况下,我都会强烈选择云存储客户端库,因为所有(或大多数)功能都可以通过它们获得,并且它们可以让您在尝试从脚本进行API调用时更加轻松。找到了它
result=get\u ipython().getoutput(cmd,split=True)
见: