使用certutil和Python下载文件

使用certutil和Python下载文件,python,cmd,Python,Cmd,我试图通过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.con

我试图通过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)
此外:

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


谢谢

首先:这个问题会使
\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.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

Popen
(当您不使用
shell=True
时)可能需要类似于
[“certutil”、“-urlcache”、“-split”、“-f”、”https://www.contextures.com/SampleData.zip“,“c:\temp\test.zip”]
问题也会导致
\t
,这在Python字符串中具有特殊意义,您应该使用
“c:\\temp\\test.zip”
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