【问题标题】:subprocess in python: file does not existpython中的子进程:文件不存在
【发布时间】:2019-12-08 16:39:00
【问题描述】:

我在尝试使用 subprocess 命令从我的 Mac 启动应用程序时遇到此错误。

我试过了,它仍然可以正常工作

import subprocess

appname = "Microsoft Word"
appname1 = appname + ".app"
subprocess.Popen(["open", "-n", "/Applications/" + appname1], stdout=subprocess.PIPE)

但是,当我将它应用到我的函数时。它说文件不存在。

import re
import subprocess

def myCommand(command):
    elif 'launch' in command:
        reg_ex = re.search('launch(.*)', command)
        if reg_ex:
            appname = reg_ex.group(1)
            appname1 = appname + ".app"
            subprocess.Popen(["open", "-n", "/Applications/" + appname1], stdout=subprocess.PIPE)

它返回如下:

Command: Launch Microsoft Word
The file /Applications/ microsoft word.app does not exist.

【问题讨论】:

  • /Applications/ 和“Microsoft word”之间的空格是错字还是错误消息中实际存在?如果它确实存在,那可能是你的问题......也许尝试一个正则表达式,消除启动词和表达式的其余部分之间的 no y 空格?例如。 re.search('launch\s*(.*)'
  • @GMc:哦,它奏效了。谢啦。我真的很傻,没有意识到问题出在两者之间。

标签: python-3.x macos subprocess


【解决方案1】:

问题是您的正则表达式在launch 的参数之前捕获了空格,导致完整的文件名像/Applications/ microsoft word.app 而不是/Applications/microsoft word.app

那(或简单的str.split 或更好:shlex.split)会解决它:

re.search('launch\s+(.*)', command)

请注意,'launch' in command 检测命令是否真的是launch 有点脆弱。如果 参数 包含 launch 会怎样。使用shlex.split 能够正确解析您的命令行(支持引号):

import shlex

command = ' launch "my application"'

args = shlex.split(command)
# at this point, args = ['launch', 'my application']
if args[0] == "launch" and len(args)==2:
    p = subprocess.Popen(["open","-n",os.path.join("/Applications",args[1])],stdout=subprocess.PIPE)

【讨论】:

  • 天啊!有效。并感谢您的建议。我肯定会用它。
猜你喜欢
  • 2012-10-21
  • 1970-01-01
  • 1970-01-01
  • 2018-05-05
  • 1970-01-01
  • 1970-01-01
  • 2020-02-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多