【问题标题】:printing to terminal using Applescripts through Python通过 Python 使用 Applescripts 打印到终端
【发布时间】:2016-08-28 20:37:26
【问题描述】:

我正在使用 python 来运行一些 Applescript 脚本。我希望能够在“重复”循环中打印到屏幕上。我目前正在做的一个愚蠢的例子是:

from subprocess import Popen, PIPE

##### My applescript script

scpt = '''                                                                                                                                            
set letters to {"A", "B", "C"}                                                                                                                        
repeat with theLetter in letters                                                                                                                      
     do shell script "echo " & theLetter                                                                                                              
end repeat                                                                                                                                            
'''

#### run the script
p = Popen(['osascript', '-'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate(scpt)
print stdout, stderr

现在,这样做只会将最后一个条目打印到终端(在本例中为“C”)。有没有办法在每次迭代期间将其打印到终端。即

A
B
C

谢谢!

【问题讨论】:

    标签: python terminal applescript


    【解决方案1】:

    如果您不介意输出到 stderr,那么以下是我使用的最简单的方法:

    from subprocess import Popen, PIPE
    
    ##### My applescript script
    
    scpt = '''
    set letters to {"A", "B", "C"}
    repeat with theLetter in letters
         log theLetter
    end repeat
    '''
    
    #### run the script
    p = Popen(['osascript', '-'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
    stdout, stderr = p.communicate(scpt)
    print stdout, stderr
    

    这将为您提供以下信息(注意前导空格,因为标准输出为空):

     A
    B
    C
    

    如果使用log,另一种选择是结合标准输出和标准错误,所以你最终得到:

    from subprocess import Popen, PIPE, STDOUT
    
    ##### My applescript script
    
    scpt = '''
    set letters to {"A", "B", "C"}
    repeat with theLetter in letters
         log theLetter
    end repeat
    '''
    
    #### run the script
    p = Popen(['osascript', '-'], stdin=PIPE, stdout=PIPE, stderr=STDOUT)
    stdout, stderr = p.communicate(scpt)
    print stdout
    

    给你:

    A
    B
    C
    

    当然,因为这是使用communicate,它只会在过程完成时给你输出,如果你想在屏幕上显示进度,一种方法是根本不捕获stderr,让Applescript 打印到 stderr(使用 log),完成后将 Python 输出到 stdout。

    【讨论】:

      猜你喜欢
      • 2014-06-18
      • 1970-01-01
      • 2014-11-02
      • 2015-11-04
      • 1970-01-01
      • 2012-10-20
      • 1970-01-01
      • 2013-06-27
      • 2013-09-14
      相关资源
      最近更新 更多