当使用带有os.system
的start
命令时,如何运行需要包含空格的文件路径的命令
例如:
# path_d[key] = C:UsersJohnDocumentsSome File With Space.exe
path = path_d[key]
os.system("start {0}".format(path))
当我尝试运行它时,我最终收到一个错误,说:
Windows cannot find 'C:UsersJohnDocumentsSome.'. Make sure you typed the name correctly, and then try again.
我执行以下操作
path = path_d[key]
os.system(r'start "{0}"'.format(path))
因此,用双引号将路径括起来。 这样,它将处理路径中的空格。 如果没有要打开的默认应用程序,则可能会打开命令提示符。因此,如果是文本文件,请执行以下操作
os.system(r'notepad "{0}"'.format(path))
您需要正确转义path
中的特殊字符,这可能很容易完成:
path = r"C:UsersJohnDocumentsSome File With Space.exe"
要在 Windows 下执行它:
import os
os.system(r"C:UsersJohnDocumentsSome File With Space.exe")
编辑
根据OP的要求:
path_dict = {"path1": r"C:UsersJohnDocumentsSome File With Space.exe"}
os.system('{}'.format(path_dict["path1"]))