【发布时间】:2018-07-14 07:32:14
【问题描述】:
我正在开发一个模块,以将来自 tensorflow 的保存/恢复检查点从 colaboratory 添加到谷歌云存储(参见:https://github.com/mixuala/colab_utils)。我的代码使用 ipython 魔术和 shell 命令在笔记本外壳上运行。但是我发现你不能从 python 模块中导入这些方法(dooh!)所以现在我正在尝试转换为 python native。
如何从 `get_ipython().system.raw() 获得 stdout?
我想获得与以下相同的值:
# ipython shell command
!gsutil ls $bucket_path
我尝试使用get_ipython().system_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"`
【问题讨论】:
标签: ipython jupyter-notebook gsutil google-colaboratory