0

I'd like to run some terminal command within my Mac program. For example, I normally use mate abc.txt or python abc.py from my shell to open Text Mate or running python script.

How can I do the same thing with Cocoa/Objective-C?

I thought about this method, but I prefer just running in one line.

For example, when users enter "python abc.py", I just run the command as if it's in the Terminal.app. Python's equivalent command is os.system().

inputItem <-- inputItem TextField

NSString* item = [inputItem stringValue];
[NSRuncommandLikeShell item]; <-- ????

The environment variables should be retained so that I don't need to run '/usr/bin/python'.

EDIT

I can use ~/.MacOSX/environment.plist file for setup path environment. Or, I also could use this utility for GUI.

Community
  • 1
  • 1
prosseek
  • 182,215
  • 215
  • 566
  • 871

2 Answers2

3

You can use an NSTask object. If you don't like all of the setup that goes in to this, you can create an NSTask category that does it for you.

Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
1

You can use the C runtime system() call.

#include <stdlib.h>

system([item UTF8String]);
Ferruccio
  • 98,941
  • 38
  • 226
  • 299
  • It seems to work, but the shell PATH is lost to get this error : `e: command not found` – prosseek Mar 10 '11 at 18:15
  • Try to avoid running `system()` calls in your code. They are localized to their own sessions (calling `system("cd ~/Desktop")` doesn't carry the current working directory to the next `system()` call), and are less safe than using `NSTask`. If I remember correctly, they're also pretty buggy, and prone to security hacks. – Itai Ferber Mar 10 '11 at 18:55