task.pyuses the #! thing and is set to be executable (by the user only). The code looks for an int in argv and a second arg that tells whether to examine the environment variable dictionary.
The first attempt just launches the task without setting it up first.
The second example does the setup. The path p2 (to Python directly) isn't used in these versions but I left it in. For a while, I was getting errors when I tried to setup the task and then launch it unless I fed it to Python first and gave the script path as an argument. Then, the errors just stopped. I can't recreate the problem. This kind of bug that "just disappeared" happened with the environment dictionary as well. No clue as to why.
Of note here is that the arguments must be in a list or array, and that the int argment must be converted to a string. The error if not is weird (but at least we're pointed to the correct line):
Otherwise we get this:
Next, we instantiate the task and then set its arguments and environment, having modified the dict to have an extra key/value pair:
The ultimate line of output is from the task and shows that we did get the modified environment.
And in the last example, we use an NSFileHandle and redirect standard output. This could be useful in the case where you don't have full control over the task that is being executed. I found that
NSFileHandle.fileHandleForWritingAtPath_apparently requires the file to already exist.
The redirect is good, but I couldn't get the file read to work. I tried before and after launch, and I tried re-grabbing the file handle, and I also tried
readDataToEndOfFile. Not sure what's up with that yet.
[UPDATE: Perhaps the answer has something to do with NSPipe (here). ]