使用certutil和Python下载文件

2024-09-19 23:33:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过Python调用cmd命令来下载该文件。在cmd中运行此命令时:

certutil -urlcache -split -f https://www.contextures.com/SampleData.zip c:\temp\test.zip

文件下载时没有任何问题,但是当我通过Python运行该命令时,文件没有被下载。我试过:

import subprocess
command = "certutil -urlcache -split -f https://www.contextures.com/SampleData.zip c:\temp\test.zip"

subprocess.Popen([command])
subprocess.call(command, shell=True)

此外:

os.system(command)

你知道为什么这样不行吗?任何帮助都将不胜感激

谢谢


Tags: 文件https命令cmdcomwwwziptemp
2条回答

第一:这个问题会使\t在Python(和其他语言)中具有特殊意义,您应该使用"c:\\temp\\test.zip",或者您必须使用前缀r来创建原始字符串r"c:\temp\test.zip"

第二:当您不使用shell=True时,您需要如下列表

["certutil", "-urlcache", "-split", "-f", "https://www.contextures.com/SampleData.zip", "c:\\temp\\test.zip"]

有时人们只是使用split(' ')来创建它

"certutil -urlcache -split -f https://www.contextures.com/SampleData.zip c:\\temp\\test.zip".split(" ")

然后您可以测试这两个版本

cmd = "certutil -urlcache -split -f https://www.contextures.com/SampleData.zip c:\\temp\\test.zip"

Popen(cmd.split(' '))

Popen(cmd, shell=True)

编辑:

如果您将使用更复杂的命令(即字符串中带有" "),那么您可以使用标准模块shlex和命令shlex.split(cmd)。要使\\保持在路径中,您可能需要`posix=False

import shlex

cmd = "certutil -urlcache -split -f https://www.contextures.com/SampleData.zip c:\\temp\\test.zip"

Popen(shlex.split(cmd, posix=False))

例如,这给出了包含4个元素的错误列表

' text "hello world"  other'.split(' ')

[' text', '"hello', 'world"', ' other']

但这给出了包含3个元素的正确列表

shlex.split(' text "hello world"  other')

[' text', 'hello world', ' other']

此外,可以指定一个raw字符串,该字符串不会解释转义序列,例如\t

Python 3.8.4 (tags/v3.8.4:dfa645a, Jul 13 2020, 16:46:45) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("now\time")
now     ime
>>> print(r"now\time")
now\time
>>> print('now\time')
now     ime
>>> print(r'now\time')
now\time

相关问题 更多 >