简体   繁体   English

使用Python下载.Jar文件

[英]Downloading .Jar File using Python

I am attempting to download a file from the internet using Python along with the sys and urllib2 modules. 我正在尝试使用Python以及sys和urllib2模块从Internet下载文件。 The general idea behind the program is for the user to input the version of the file they want to download, 1_4 for example. 该程序的基本思想是让用户输入要下载的文件的版本,例如1_4。 The program then adds the user input and the "/whateverfile.jar" to the url and downloads the file. 然后,该程序将用户输入和“ /whateverfile.jar”添加到URL并下载文件。 My problem arises when the program inserts the "/whateverfile.jar" instead of inserting onto the same line the program inserts the "/whateverfile.jar" onto a new line. 当程序将“ /whateverfile.jar”插入到同一行而不是插入到同一行时,出现了我的问题。 Which causes the program to fail to download the .jar properly. 这会导致程序无法正确下载.jar。

Can anyone help me with this? 谁能帮我这个? The code and output is below. 代码和输出如下。

Code: 码:

import sys
import urllib2

print('Type version of file you wish to download.')
print('To download 1.4 for instance type "1_4" using underscores in place of the            periods.')
W = ('http://assets.file.net/')
X = sys.stdin.readline()
Y = ('/file.jar')
Z = X+Y
V = W+X
U = V+Y
T = U.lstrip()
print(T)

def JarDownload():
  url = "T"

  file_name = url.split('/')[-1]
  u = urllib2.urlopen(url)
  f = open(file_name, 'wb')
  meta = u.info()
  file_size = int(meta.getheaders("Content-Length")[0])
  print "Downloading: %s Bytes: %s" % (file_name, file_size)

  file_size_dl = 0
  block_sz = 8192
  while True:
      buffer = u.read(block_sz)
      if not buffer:
          break

      file_size_dl += len(buffer)
      f.write(buffer)
      status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
      status = status + chr(8)*(len(status)+1)
      print status,

  f.close()

Output: 输出:

Type version of file you wish to download.
To download 1.4 for instance type "1_4" using underscores in place of the periods.
1_4
http://assets.file.net/1_4
/file.jar

I am currently not calling the JarDownload() function at all until the URL will display as a single line when printed to screen 目前,我完全不调用JarDownload()函数,直到在打印到屏幕上时URL显示为一行时为止

When you type the input and hit Return, the sys.stdin.readline() call will append the new line symbol to the string and return it. 当您键入输入并单击Return时, sys.stdin.readline()调用会将新的行符号附加到字符串中并返回它。 To get the desired effect, you should strip the new line from the input before using it. 为了获得理想的效果,应在使用前从输入中去除新行。 This should work: 这应该工作:

X = sys.stdin.readline().rstrip()

As a side note, you should probably give more meaningful names to your variables. 附带说明,您可能应该给变量赋予更有意义的名称。 Names like X, Y, Z, etc. say nothing about the variables content and make even simple operations, like your concatenations, unnecessarily hard to understand. 诸如X,Y,Z等之类的名称对变量的内容一无所知,甚至使诸如串联之类的简单操作变得不必要地难以理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM