需要Python3引用语法帮助

时间:2014-12-29 06:45:59

标签: python python-3.x

我想传输一个文件但不熟悉python脚本。下面的代码不确定我是否可以这样做。

  if os.path.exists(fileName):
    outputFile = open(fileName, "ab")
  else
    outputFile = open(fileName, "wb")


  with urllib.request.urlopen(url) as response, outputFile as out_file:
             data = response.read()
             out_file.write(data)

这是错误。

Traceback (most recent call last):
  File "ToshibaCopyFile.py", line 51, in <module>
    with urllib.request.urlopen(url) as response, outputFile as out_file:
  File "/usr/lib/python3.2/urllib/request.py", line 139, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib/python3.2/urllib/request.py", line 376, in open
    response = meth(req, response)
  File "/usr/lib/python3.2/urllib/request.py", line 488, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python3.2/urllib/request.py", line 414, in error
    return self._call_chain(*args)
  File "/usr/lib/python3.2/urllib/request.py", line 348, in _call_chain
    result = func(*args)
  File "/usr/lib/python3.2/urllib/request.py", line 496, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 503: Service Unavailable

我知道我本可以用这种方式编写(abit冗余,试图简化它)

  if os.path.exists(fileName):
    with urllib.request.urlopen(url) as response, open(fileName, "ab") as out_file:
             data = response.read()
             out_file.write(data)
  else
    with urllib.request.urlopen(url) as response, open(fileName, "wb") as out_file:
             data = response.read()
             out_file.write(data)

请任何建议

1 个答案:

答案 0 :(得分:0)

埃里克,

我认为你在这里遇到至少两个问题。您可能还遇到了尝试获取数据的Web服务器的实际问题;但是你的代码首先要解决几个问题。

首先注意: urlib 似乎不支持上下文管理。所以我想你会想要这样的东西:

#!//usr/bin/python
import contextlib, urllib

url = 'http://stackoverflow.com/'
outfilename = '/tmp/foo.out'

with contextlib.closing(urllib.urlopen(url)) as response, open(outfilename, 'w') as output_file:
    output_file.write(response.read())

请注意, with 语句必须包含打开资源和别名( as )的调用。我不知道如何在封闭块中打开它并尝试使用语句行在上执行别名会起作用...而且我很确定它不是受支持的语法。 (如果您想自己仔细阅读这些内容,请参考以下内容:https://docs.python.org/2/reference/compound_stmts.html#the-with-statement)。

请注意,我正在使用 contextlib 提供的包装器来实现围绕 urllib.urlopen()调用返回的对象的上下文管理。

注意:在Python3中,这将略有不同:

#!/usr/bin/python3
import contextlib, urllib
url = 'http://www.stackoverflow.com/'
outfilename = '/tmp/output.out'
## Python 3 differences start here:
with contextlib.closing(urllib.request.urlopen(url)) as response, \
     open(outfilename, 'w') as output_file:
  output_file.write(str(response.read()))
## urllib.urlopen becomes urllib.request.urlopen()
## and the bytes returned by the read() method must be explicity
## converted into a string for our file write()

看看是否有帮助。使用知道工作的URL来检查该代码;然后看看您是否可以解决阻止您的HTTP访问目标的任何问题。