Python 调用 wget 命令下载报错如何解决
save_path = os.path.join("/home/shenjianlin/pdf_file",name)
try:
cmd = (“sudo wget -P -N -o -c -O {} {}”.format(save_path, link))
ref = subprocess.call(cmd, shell=True)
if ref != 0:
print (“can’t get download”)
else:
print(“finishing downloading {} page {} row data”.format(i,j))
except Exception as e :
print(‘download error has happend’)
print (e)
报错如下:
/bin/sh: $’\350\266\213\345\212\277\345\261\225\346\234\233-82\351\241\265’: command not found
can’t get download
《 2018 暑期旅游消费趋势预测》:亲子客群占主流 高档海岛酒店占比提升-6 页.pdf
途牛旅游网
2018-06-22 18:01:38
http://pdf1.qimingpian.com/announcement_real/5b2c9ac2320c7.pdf
wget: missing URL
Usage: wget [OPTION]… [URL]…
Try `wget --help’ for more options.
can’t get download
Python 调用 wget 命令下载报错如何解决
帖子标题说的是用Python调用wget命令下载时出错了。这问题很常见,通常出在命令拼写、文件路径或者wget本身没装好。
最稳的办法是别用os.system调外部命令,直接用Python的requests库来下,又干净又不容易出错。下面给你个例子:
import requests
def download_file(url, save_path):
try:
response = requests.get(url, stream=True)
response.raise_for_status() # 检查请求是否成功
with open(save_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
print(f"文件已下载到: {save_path}")
except requests.exceptions.RequestException as e:
print(f"下载失败: {e}")
# 使用示例
download_file('https://example.com/file.zip', './file.zip')
如果你非要用wget,那得确保命令格式对,特别是URL和保存路径别写错,还有系统里得装了wget。像这样:
import subprocess
import sys
url = "https://example.com/file.zip"
output = "./file.zip"
try:
# -O 指定输出文件名
result = subprocess.run(['wget', '-O', output, url], check=True, capture_output=True, text=True)
print("下载成功")
except subprocess.CalledProcessError as e:
print(f"wget命令执行失败,返回码: {e.returncode}")
print(f"错误输出: {e.stderr}")
except FileNotFoundError:
print("错误:系统中未找到 wget 命令。请先安装 wget。")
用subprocess.run比os.system好,能抓到错误信息。第一个参数得是列表,把命令和参数分开。check=True能让命令失败时抛异常,capture_output=True能抓到输出和错误。
常见坑:URL没加引号(里面有特殊字符比如&会出问题),保存路径的目录没权限或者不存在,再就是网络问题或者wget没装。
总结:换requests库一劳永逸。
你先把 cmd 输出看看
用 sudo 的话,是不是需要输入密码才得行哦?

