【问题标题】:Python "call()" function doesn't accept path to file from "abspath()"Python“call()”函数不接受来自“abspath()”的文件路径
【发布时间】:2014-08-09 06:51:20
【问题描述】:

可能这个问题很明显,请原谅。

我想执行 shell 命令(Windows 8.1、Python 3.4)来打开带有 SVG 文件的 IE。 我是这样做的:

# imgpath = 'C:/Users/Vladimir/dot-code\\..\\graph1.svg'
tmp = FS.abspath(imgpath)
# tmp = 'C:\\Users\\Vladimir\\graph1.svg'
subprocess.call(["start", "", tmp])

看起来不错,但我在 call() 中遇到异常 - FileNotFoundError: [WinError 2] File not found.

我想罪恶的根源是“tmp”中的双斜线。我该如何解决?

【问题讨论】:

  • 为什么您的 imgpath 与您的 tmp 路径不同?
  • 我使用 GraphViz 生成图像。点代码位于“C:/Users/Vladimir/dot-code/graph1.dot”中。我将生成的图像保存在上一个目录中。

标签: python python-3.x cmd window python-3.4


【解决方案1】:

您不应该传递空字符串。 (我猜,您的意思是将命令和参数分开。)。删除空白字符串。只需传递start 和路径即可。

除此之外start 不是真正的程序,而是cmd 的内置命令。使用cmd /c

subprocess.call(['cmd', '/c', 'start', tmp])

或传递shell=True关键字参数:

subprocess.call(['start', tmp], shell=True)

顺便说一句,在 windows 上,你可以使用os.startfile:

import os
os.startfile(tmp)

【讨论】:

  • 它不起作用。根据docs,开始的第一个参数是“标题”。但是感谢 startfile!
  • @Vladimir,“标题”是可选的。如果您仅指定一个解释为filename 的参数。
  • @Vladimir,如果subprocess.call 解决方案不起作用,有两种选择:(1)使用shell=Truesubprocess.call(['start', tmp], shell=True)。 (2) 显式调用cmd.exe:subprocess.call(['cmd', '/c', 'start', tmp])。我刚刚更新了答案以包含此内容。
  • shell=True 已修复!谢谢!
猜你喜欢
  • 1970-01-01
  • 2019-09-28
  • 2023-03-18
  • 2021-04-26
  • 2016-02-11
  • 2018-11-08
  • 1970-01-01
  • 2019-06-05
  • 2014-09-19
相关资源
最近更新 更多