简体   繁体   English

如何使用 Python 执行的 AppleScript 打印到终端?

[英]How do I print to terminal with an AppleScript executed with Python?

I have a Python script that executes an apple script.我有一个执行苹果脚本的 Python 脚本。 I'd like to print to terminal from within the apple script.我想从苹果脚本中打印到终端。

Here is my Python code.这是我的 Python 代码。

import applescript

myfunction = """

do shell script "echo " & "words to terminal"

"""

def runfunction():
    applescript.tell.app("Terminal", myfunction, background = False)

And then I execute this with python -c 'import myapplescript; print myapplescript.runfunction()'然后我用python -c 'import myapplescript; print myapplescript.runfunction()' python -c 'import myapplescript; print myapplescript.runfunction()'

I've tried to print to terminal from within the apple script using the "do shell script" phrase and also copy "Hello World!" to stdout我尝试使用“do shell 脚本”短语从苹果脚本中打印到终端,并copy "Hello World!" to stdout copy "Hello World!" to stdout

import applescript

That is not a very good library.那不是一个很好的图书馆。 If your needs are simple, I would just use subprocess directly .如果您的需求很简单,我会直接使用 subprocess 。

Also be aware that osascript is limited in its own IO support.另请注意, osascript在其自身的 IO 支持方面受到限制。 There's no built-in way to access stdin, and the only data that gets written to stdout is the last value (if any) returned at the end of the script.没有访问标准输入的内置方法,写入标准输出的唯一数据是脚本末尾返回的最后一个值(如果有)。 (You can write to stderr at any time using the log command, though that will have its own set of issues.) (您可以随时使用log命令写入 stderr,尽管这会有自己的一系列问题。)

If you want to access stdin/stdout directly in your AppleScript code, you'll have to use Cocoa's NSFileHandle class.如果您想直接在 AppleScript 代码中访问标准输入/标准输出,则必须使用 Cocoa 的NSFileHandle class。 I wrote a File library some years back that provided easy-to-use wrappers around that, though I don't maintain or support it.几年前我写了一个文件,它提供了易于使用的包装器,尽管我不维护或支持它。

If your needs are more advanced—eg you want to call one or more AppleScript handlers or pass anything more complex than simple (short) strings—and you have PyObjC installed, you'd be better using [this library] ( https://pypi.org/project/py-applescript/ ) or the AppleScript-ObjC bridge .如果你的需求更高级——例如你想调用一个或多个 AppleScript 处理程序或传递比简单(短)字符串更复杂的东西——并且你安装了 PyObjC,你最好使用[这个库]( https:// pypi.org/project/py-applescript/ )或 AppleScript-ObjC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM