问题描述
我想在 JavaScript for自动化(JXA),然后将一个字符串发送到该子进程的stdin,其中可能包括换行符,shell metas等.以前的AppleScript对此方法使用了bash的<<<
运算符,字符串连接和quoted form of
字符串.如果我可以信赖的JavaScript与quoted form of
等效,可以得到所有极端情况,则可以使用相同的方法.为此,我正在研究正则表达式方法.
I would like to start a subprocess in JavaScript for Automation (JXA) and send a string to that subprocess's stdin which might include newlines, shell metas, etc. Previous AppleScript approaches for this used bash's <<<
operator, string concatenation, and quoted form of
the string. If there was a JavaScript equivalent of quoted form of
that I could trust to get all of the edge cases, I could use the same approach; I'm investigating regex methods toward that end.
但是,我想既然可以从JXA访问unistd.h
,为什么不尝试直接调用$.pipe
,$.fork
和$.execlp
? $.pipe
看起来它应该以2个整数组成的数组作为其参数,但我尝试过的所有方法均无效:
However, I thought since we have access to unistd.h
from JXA, why not try to just call $.pipe
, $.fork
, and $.execlp
directly? $.pipe
looks like it should take an array of 2 integers as its parameter, but none of the things that I have tried worked:
ObjC.import('unistd')
$.pipe() // Error: incorrect number of arguments
$.pipe([]) // segfault
$.pipe([3,4]) // segfault
$.pipe([$(), $()]) // segfault
var a = $(), b=$()
$.pipe([a,b]) // segfault
$.pipe($([a,b])) // NSException without a terribly helpful backtrace
$.pipe($([$(3), $(4)])) // segfault
var ref = Ref('int[2]')
$.pipe(ref)
ref[0] // 4, which is close!
有什么建议吗?
推荐答案
我找到了一种可行的方法,使用可可代替stdio:
I found an approach that works, using Cocoa instead of stdio:
ObjC.import('Cocoa')
var stdin = $.NSPipe.pipe
var stdout = $.NSPipe.pipe
var task = $.NSTask.alloc.init
task.launchPath = "/bin/cat"
task.standardInput = stdin
task.standardOutput = stdout
task.launch
var dataIn = $("foo$HOME'|\"").dataUsingEncoding($.NSUTF8StringEncoding)
stdin.fileHandleForWriting.writeData(dataIn)
stdin.fileHandleForWriting.closeFile
var dataOut = stdout.fileHandleForReading.readDataToEndOfFile
var stringOut = $.NSString.alloc.initWithDataEncoding(dataOut, $.NSUTF8StringEncoding).js
console.log(stringOut)
这篇关于管道到JXA的子流程stdin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!