I'm working on a module to add save/restore checkpoints from tensorflow to google cloud storage from colaboratory
(see: https://github.com/mixuala/colab_utils) . My code works from a notebook shell using ipython
magic and shell commands. But I discovered that you cannot import these methods from a python module (dooh!) So now I'm trying to convert to python native.
How do I get stdout
from `get_ipython().system.raw()?
I want to get the same value as:
# ipython shell command
!gsutil ls $bucket_path
I tried to use get_ipython().system_raw()
but I am not getting a value from 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
is there a better way to do this?
[SOLVED]
here is a better way to do it based on the answer below:
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"`