我试图通过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)知道为什么这不管用吗?任何帮助都将不胜感激。
谢谢!
发布于 2020-08-24 20:17:55
首先:问题可以使\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']但这给出了包含三个元素的正确列表
shlex.split('--text "hello world" --other')
['--text', 'hello world', '--other']发布于 2020-08-25 12:09:21
此外,还可以指定不解释转义序列(如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\timehttps://stackoverflow.com/questions/63567502
复制相似问题