您如何从 python 脚本成功调用 gsutil rsync?
How do you successfully invoke gsutil rsync from a python script?
我正在尝试执行以下行
gsutil -m rsync s3://input gs://output
在 python 中。当 运行 在 shell 终端中使用此行时,它工作正常。但是,我试图通过使用以下行在 python 脚本中 运行 这样做。
subprocess.Popen(["gsutil", "-m", "rsync", "s3://input", "gs://output"])
然而它永远挂起。它输出以下内容:
Building synchronization state...
Starting synchronization...
bash命令成功打印:
Building synchronization state...
Starting synchronization...
Copying s3://input/0000
[0/1 files][ 1.0 MiB/ 5.1 MiB] (number here)% Done
文件显示在我的 gs 存储桶中
我猜这是因为最后两行可能写入了 stderr 而不是 stdout。您可以尝试使用对 Popen
的调用作为上下文管理器,然后调用 communicate()
从输出流中读取吗?
proc = subprocess.Popen(["gsutil", "-m", "rsync", "s3://input", "gs://output"])
try:
outs, errs = proc.communicate(timeout=15)
# now you can do something with the text in outs and errs
except TimeoutExpired:
proc.kill()
outs, errs = proc.communicate()
我正在尝试执行以下行
gsutil -m rsync s3://input gs://output
在 python 中。当 运行 在 shell 终端中使用此行时,它工作正常。但是,我试图通过使用以下行在 python 脚本中 运行 这样做。
subprocess.Popen(["gsutil", "-m", "rsync", "s3://input", "gs://output"])
然而它永远挂起。它输出以下内容:
Building synchronization state...
Starting synchronization...
bash命令成功打印:
Building synchronization state...
Starting synchronization...
Copying s3://input/0000
[0/1 files][ 1.0 MiB/ 5.1 MiB] (number here)% Done
文件显示在我的 gs 存储桶中
我猜这是因为最后两行可能写入了 stderr 而不是 stdout。您可以尝试使用对 Popen
的调用作为上下文管理器,然后调用 communicate()
从输出流中读取吗?
proc = subprocess.Popen(["gsutil", "-m", "rsync", "s3://input", "gs://output"])
try:
outs, errs = proc.communicate(timeout=15)
# now you can do something with the text in outs and errs
except TimeoutExpired:
proc.kill()
outs, errs = proc.communicate()