【Mac】MacOS: shell script from application

本文介绍如何使用Objective-C通过NSTask启动shell脚本及Python脚本,并收集脚本输出。具体包括设置脚本路径、参数、输入输出流等步骤。

启动一个脚本

 

NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/path/to/script/sh"];
[task setArguments:[NSArray arrayWithObjects:@"yourScript.sh", nil]];
[task setStandardOutput:[NSPipe pipe]];
[task setStandardInput:[NSPipe pipe]];

[task launch];
[task release];

 

That would run the command /path/to/script/sh yourScript.sh. If you need any arguments for your script, you can add them to the array of arguments. The standard output will redirect all output to a pipe object, which you can hook into if you want to output to a file. The reason we need to use another NSPipe for input is to make NSLog work right instead of logging to the script.

 

 

**************

运行一个python脚本:

From this page, it looks like there are some some pretty complex threading concerns specific to embedding python. Is there a reason you couldn't just run these scripts in a separate process? For instance, the following -runBunchOfScripts method would run the script ten times (by calling -runPythonScript) on a parallel background queue, collecting the resulting outputs into an array of strings, and then calling your object back on the main thread once all the scripts has completed:

 

- (NSString*)runPythonScript
{
    NSTask* task = [[[NSTask alloc] init] autorelease];
    task.launchPath = @"/usr/bin/python";  
    NSString *scriptPath = [[NSBundle mainBundle] pathForResource:@"MyScript" ofType:@"py"];
    task.arguments = [NSArray arrayWithObjects: scriptPath, nil];

    // NSLog breaks if we don't do this...
    [task setStandardInput: [NSPipe pipe]];

    NSPipe *stdOutPipe = nil;
    stdOutPipe = [NSPipe pipe];
    [task setStandardOutput:stdOutPipe];

    NSPipe* stdErrPipe = nil;
    stdErrPipe = [NSPipe pipe];
    [task setStandardError: stdErrPipe];

    [task launch];        

    NSData* data = [[stdOutPipe fileHandleForReading] readDataToEndOfFile];

    [task waitUntilExit];

    NSInteger exitCode = task.terminationStatus;

    if (exitCode != 0)
    {
        NSLog(@"Error!");
        return nil;
    }

    return [[[NSString alloc] initWithBytes: data.bytes length:data.length encoding: NSUTF8StringEncoding] autorelease];
}

- (void)runBunchOfScripts
{
    dispatch_group_t group = dispatch_group_create();
    NSMutableArray* results = [[NSMutableArray alloc] init];
    for (NSUInteger i = 0; i < 10; i++)
    {
        dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSString* result = [self runPythonScript];
            @synchronized(results)
            {
                [results addObject: result];
            }
        });
    }

    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [self scriptsDidFinishWithResults: results];
        dispatch_release(group);
        [results release];
    });
}

- (void)scriptsDidFinishWithResults: (NSArray*)results
{
    NSLog(@"Do something with the results...");
}

 

 

 

### Windows 端模拟键盘操作的方法 Windows 系统提供了多种方式来实现类似 macOS 中 AppleScript 的键盘模拟功能,尤其是模拟回车、快进等操作。以下是几种主流方案: #### 1. 使用 `pywinauto` 实现键盘模拟 `pywinauto` 是一个基于 Python 的自动化测试库,可以模拟键盘和鼠标操作。它支持两种后端:`win32` 和 `uia`,分别适用于不同类型的 GUI 应用程序。 模拟回车键的示例如下: ```python from pywinauto.application import Application # 连接到目标应用程序 app = Application(backend="uia").connect(title='目标窗口标题', timeout=10) window = app.window(title='目标窗口标题') # 模拟按下回车键 window.type_keys("{ENTER}") ``` 如果需要模拟其他按键,如快进(通常为 `Ctrl + Right` 或 `Shift + F` 等),可以使用组合键方式: ```python window.type_keys("^+{RIGHT}") # Ctrl + 右箭头 ``` #### 2. 使用 `pyautogui` 控制全局键盘操作 `pyautogui` 是一个跨平台的 GUI 自动化库,适用于模拟全局键盘和鼠标操作。 模拟回车键: ```python import pyautogui pyautogui.press('enter') ``` 模拟快进操作(例如 Ctrl + Right): ```python pyautogui.hotkey('ctrl', 'right') ``` 该方法适用于任何处于前台的应用程序,无需定位特定控件或窗口。 #### 3. 使用 `SendKeys` 实现按键模拟(VBScript/PowerShell) 在脚本语言中,可以使用 `WScript.Shell` 对象的 `SendKeys` 方法来模拟键盘输入,适用于简单的自动化任务。 VBScript 示例: ```vbscript Set WshShell = WScript.CreateObject("WScript.Shell") WshShell.SendKeys "{ENTER}" ``` PowerShell 示例: ```powershell Add-Type -TypeDefinition @" using System; using System.Runtime.InteropServices; public class KeyPress { [DllImport("user32.dll")] public static extern void keybd_event(byte vk, byte scan, uint flags, IntPtr extraInfo); } "@ # 模拟按下回车 [KeyPress]::keybd_event(0x0D, 0, 0, [IntPtr]::Zero) # 模拟释放回车 [KeyPress]::keybd_event(0x0D, 0, 0x0002, [IntPtr]::Zero) ``` #### 4. 使用 `AutoHotkey` 脚本语言 `AutoHotkey` 是一个专为 Windows 设计的热键脚本语言,支持复杂的键盘和鼠标自动化操作。 模拟回车键: ```ahk Send, {Enter} ``` 模拟快进(例如 Ctrl + Right): ```ahk Send, ^{Right} ``` 该语言支持丰富的事件绑定和窗口条件判断,适合开发复杂的自动化脚本。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值