问题描述
我正在尝试通过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)
有什么想法为什么不起作用?任何帮助将不胜感激。
谢谢!
解决方法
首先:问题可能导致\t
在Python(和其他语言)中具有特殊含义,因此您应使用"c:\\temp\\test.zip"
或必须使用前缀r
来创建原始字符串{ {1}}
第二:当您不使用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
\\
例如,这给出了包含4个元素的错误列表
import shlex
cmd = "certutil -urlcache -split -f https://www.contextures.com/SampleData.zip c:\\temp\\test.zip"
Popen(shlex.split(cmd,posix=False))
但这给出了包含3个元素的正确列表
'--text "hello world" --other'.split(' ')
['--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