【问题标题】:how to get `stdout` from ipython shell command `get_ipython().system.raw()?如何从 ipython shell 命令`get_ipython().system.raw() 中获取`stdout`?
【发布时间】: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


    【解决方案1】:

    找到了。

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

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

    【讨论】:

      【解决方案2】:

      我建议使用 Google Cloud Python Client Libraries for Cloud Storage。这些库用于与 Google Cloud Platform 服务交互,它们是用一组不同的编码语言编写的。您可以在 this page 中找到 Cloud Storage 客户端库的详细文档,但我还为您编写了一个小示例代码,它返回的内容与您尝试使用的 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 &lt;YOUR_BUCKET&gt; 的结果相同,所以也许你可以从那一点开始开发。在任何情况下,我都会强烈选择 Cloud Storage Client Libraries,因为所有(或大部分)功能都可以通过它们使用,并且当您尝试从脚本进行 API 调用时,它们可以让您的生活更轻松。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-07-23
        • 2023-03-23
        • 1970-01-01
        • 1970-01-01
        • 2020-03-25
        • 2011-04-08
        • 2014-03-19
        • 2021-03-19
        相关资源
        最近更新 更多