【发布时间】:2011-11-24 02:19:45
【问题描述】:
我见过类似的问题(例如 Running a command in a new Mac OS X Terminal window ),但我需要确认此命令及其在 mac 中的预期行为(我没有)。如果有人可以在 Python 3 Mac 中运行以下内容:
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 进程(我的最终目标)。
在所有情况下,只要您“按任意键”,新终端就会消失。也请确认。
如果其中一项不起作用,我们将非常感谢您进行更正/诊断。也赞赏:是否有一种更 Python 的方式在 Mac 上生成终端然后在其上执行(sudo,扩展)bash 命令?
谢谢!
【问题讨论】:
-
$EXIT 应该做什么?
标签: python macos terminal command new-operator