如何从 ipython shell 命令 `get_ipython().system.raw() 获取 `stdout`?

how to get `stdout` from ipython shell command `get_ipython().system.raw()?

我正在开发一个模块,将 save/restore 检查点从 tensorflow 添加到 google 来自 colaboratory 的云存储(参见:https://github.com/mixuala/colab_utils)。我的代码在笔记本 shell 上使用 ipython 魔法和 shell 命令运行。但我发现您无法从 python 模块导入这些方法(哦!)所以现在我正在尝试转换为 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"` 

我建议使用 Google Cloud Python Client Libraries for Cloud Storage. These libraries are used to interact with Google Cloud Platform services, and they are written in a set of different coding languages. You can find a detailed documentation for Cloud Storage's Client Library in this page,但我也为您编写了一个小示例代码,returns 与来自的内容相同您尝试使用的 gsutil ls <YOUR_BUCKET> 命令。

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))

运行 这段代码的输出如下:

gs://<YOUR_BUCKET_NAME>/file_1.png
gs://<YOUR_BUCKET_NAME>/file_2.png
gs://<YOUR_BUCKET_NAME>/file_3.png

与运行gsutil ls <YOUR_BUCKET>的结果相同,所以也许你可以从那一点发展。无论如何,我会强烈选择 Cloud Storage Client Libraries,因为所有(或大多数)功能都可以通过它们使用,并且当您尝试从脚本进行 API 调用时,它们可以让您的生活更轻松。

找到了。

result = get_ipython().getoutput(cmd, split=True)

参见:https://github.com/ipython/ipython/blob/master/IPython/core/interactiveshell.py