OSX和Python3:在新终端中执行bash命令时的行为?

2024-05-20 05:09:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我见过类似的问题(例如Running a command in a new Mac OS X Terminal window),但我需要确认这个命令及其在mac中的预期行为(我没有)。如果有人可以在Python 3mac中运行以下命令:

import subprocess, os
def runcom(bashCommand):
     sp = subprocess.Popen(['osascript'], stdin=subprocess.PIPE, stderr=subprocess.PIPE)
     sp.communicate('''tell application "Terminal"\nactivate\ndo script with command "{0} $EXIT"\nend tell'''.format(bashCommand))

runcom('''echo \\"This is a test\\n\\nThis should come two lines later; press any key\\";read throwaway''')
runcom('''echo \\"This is a test\\"\n\necho \\"This should come one line later; press any key\\";read throwaway''')
runcom('''echo \\"This is testing whether I can have you enter your sudo pw on separate terminal\\";sudo ls;\necho \\"You should see your current directory; press any key\\";read throwaway''')

首先,也是最基本的,“生成新终端并执行”命令是否正确?(作为参考,这个版本的runcom函数来自this answer below,比我原来的版本干净得多。)

至于实际的测试:第一个测试内部双转义\\n字符是否真正起作用。第二个测试,我们可以在“脚本”中放入(未替换的)新行,并且它仍然像分号一样工作。最后,最后一个测试您是否可以在单独的终端中调用sudo进程(我的最终目标)。在

在任何情况下,新的终端应该在你“按任意键”后消失。请确认这一点。在

如果其中一个不起作用,最好能进行矫正/诊断。同样值得赞赏的是:在Mac上生成一个终端,然后在其上执行(sudo,extended)bash命令,有没有一种更像python的方式呢?在

谢谢!在


Tags: key命令echo终端readissudoany
2条回答

我没有Python3,但是我稍微编辑了一下您的runcom函数,它应该可以工作:

def runcom(bashCommand):
    sp = subprocess.Popen(['osascript'], stdin=subprocess.PIPE, stderr=subprocess.PIPE)
    sp.communicate('''tell application "Terminal"\nactivate\ndo script with command "{0} $EXIT"\nend tell'''.format(bashCommand))

[...] its expected behavior [...]

这很难回答,因为这些命令执行的是I期望它们做的事情,而这可能不是您期望它们做的事情。在

As for the actual tests: the first one tests that internal double escaped \n characters really work.

带有双反斜杠的\\n确实工作正常,因为它导致echo发出换行符。但是,echo不会发出双引号。在

The second tests that we can put (unescaped) newlines into the "script" and still have it work just like semicolon.

这也管用。在

Finally, the last one tests whether you can call a sudo process in a separate terminal (my ultimate goal).

没有理由不这样做,事实上确实如此。在

In all cases, the new terminal should disappear as soon as you "press any key". Please also confirm this.

由于以下几个原因,这种做法行不通:

  • ^默认情况下,bash中的{}将读取整行,而不仅仅是一个字符
  • 在执行您提供的脚本之后,终端中的shell没有理由退出
  • 即使shell退出,用户也可以配置终端.app在shell退出后不关闭窗口(这甚至是默认设置)

其他问题:

  • 您提供给osascript的脚本将在执行之前出现在终端窗口中。在上面的示例中,用户将看到每个“This is a test[…]”两次。在
  • 我不知道$EXIT应该做什么
  • ls命令只会在新终端窗口中的当前工作目录始终是用户的主目录的情况下向用户显示“当前目录”
  • throwaway在脚本bashCommand退出后将不可用

最后,这个脚本在python3下根本不起作用,因为它以TypeError崩溃:communicate()以字节字符串作为参数,而不是字符串。在

Also appreciated: is there a more pythonic way of spawning a terminal on Mac [...]

你应该去调查一下!它不一定更像Python,但至少你可以消除一些间接层。在

相关问题 更多 >