如何在 astropy 中从 URL 打开 FITS 文件?

How do I open a FITS file from a URL in astropy?

我在 URL 有一个 .fits 文件,我想读入 Python 就好像它就在我的机器上一样。我试过的是:

import urllib2 as url, astropy.io.fits as fits
target_url = 'https://s3.amazonaws.com/bdnyc/spex_prism_U50171_0835%2B19_chiu06.fits'
obj = url.urlopen(target_url)
dat = fits.open(obj)

但我刚得到 IOError: File-like object does not have a 'write' method, required for mode 'ostream'.

即使我在 fits.open() 中设置 mode='readonly' 它也说它不能写入类文件对象。

有没有办法从 URL 打开 .fits 文件?或者将 urlopen() 返回的 .fits 文件字节转换回 HDUList?

基于 documentation of astropy.io.fits.open,它可以选择从 URL:

中读取 .fits 文件的内容

cache : bool, optional

If the file name is a URL, download_file is used to open the file. This specifies whether or not to save the file locally in Astropy’s download cache (default: True).

这意味着您不必使用 urllib2。您可以立即将 target_url 馈送到 fits.open,因为它会在打开 URL 之前调用 astropy.utils.data.download_file。请参阅下面的代码。

In [1]: import astropy.io.fits as fits

In [2]: target_url = 'https://s3.amazonaws.com/bdnyc/spex_prism_U50171_0835%2B19_chiu06.fits'

In [3]: dat = fits.open(target_url)

In [4]: dat
Out[4]: [<astropy.io.fits.hdu.image.PrimaryHDU at 0x219a9e8>]