首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >applescript将文本传递给python脚本-标准输出的位被截断

applescript将文本传递给python脚本-标准输出的位被截断
EN

Stack Overflow用户
提问于 2018-08-05 09:26:40
回答 1查看 256关注 0票数 0

我正在尝试使用applescript将字符串传递给python脚本(我的最终用途是处理来自icloud的注释)。然而,由于某些原因,当我尝试使用print语句进行测试时,它会产生奇怪的结果。

下面是applescript:

代码语言:javascript
复制
set s to "here is a

long string

with

line breaks"

do shell script "python t3.py " & quoted form of s

下面是t3.py:

代码语言:javascript
复制
import sys 
print("about to print whole argument list") 
print(sys.argv)
print("printed whole argument list")

当我调用调用python脚本的applescript时,它输出了一些非常奇怪的东西:

printed whole argument listng string\n\nwith\n\nline breaks']

但是,如果我注释掉python脚本的最后一行,它将打印:['t3.py', 'here is a \n\nlong string\n\nwith\n\nline breaks'],这是很难纠正的(它只删除了预期打印的第一行)。

我的第一个假设是这是Python端的某种流缓冲,所以我在每个打印调用中都添加了flush=True。输出没有变化。

这到底是怎么回事?我使用的是python 3.6.4。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-06 07:48:40

您遇到了文本中换行符编码不一致的问题。不同的OSes以不同的方式表示文本中的行尾: unix (及其衍生产品,如macOS)使用换行符(有时写成\n);DOS (及其衍生产品Windows)使用换行符后跟回车符(\n\r);老式macOS(在OS X之前)仅使用回车符(\r)。

AppleScript可以追溯到Mac的前OS X时代,现在仍然使用回车符。在与操作系统的其余部分对话时,它有时会转换为unix约定,但并不总是如此。这里发生的情况是,您的python脚本正在使用换行符生成输出,AppleScript的do shell script命令正在捕获其输出并转换为回车符约定,并且它永远不会被转换回来。当它被发送到Terminal时,回车符使它返回到第一列,而不是下一行,因此输出的每一“行”都打印在最后一行的顶部。

如何修复它(或者它是否需要修复)取决于更大的上下文,即您实际要对输出做什么。在许多上下文中(包括仅在命令行上运行它),您可以通过tr '\r' '\n\管道输出输出,以将输出中的回车转换回换行符:

代码语言:javascript
复制
$ osascript t3.applescript 
printed whole argument listg string\n\nwith\n\nline breaks']
$ osascript t3.applescript | tr '\r' '\n'
about to print whole argument list
['t3.py', 'here is a\n\nlong string\n\nwith\n\nline breaks']
printed whole argument list

编辑:至于如何让AppleScript生成带有unix风格的分隔符的结果...我没有看到一种简单的方法,但您可以使用文本替换函数from here将CR转换为LF:

代码语言:javascript
复制
on replaceText(find, replace, subject)
    set prevTIDs to text item delimiters of AppleScript
    set text item delimiters of AppleScript to find
    set subject to text items of subject

    set text item delimiters of AppleScript to replace
    set subject to subject as text
    set text item delimiters of AppleScript to prevTIDs

    return subject
end replaceText


set s to "here is a

long string

with

line breaks"

set CRstring to do shell script "python t3.py " & quoted form of s

set LFstring to replaceText("\r", "\n", CRstring)

您还可以创建一个特殊用途的函数:

代码语言:javascript
复制
on CR2LF(subject)
    set prevTIDs to text item delimiters of AppleScript
    set text item delimiters of AppleScript to "\r"
    set subject to text items of subject

    set text item delimiters of AppleScript to "\n"
    set subject to subject as text
    set text item delimiters of AppleScript to prevTIDs

    return subject
end CR2LF
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51690749

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档