alphanumeric
alphanumeric

Reputation: 19329

How to pass App argument to os.system()

I am able to start application using quite simple syntax. Example

app="/Applications/MyApp/myAppExecutable"
file="/Users/userName/Pictures/myPicture.jpg"

cmd="open -a '%s' '%s'" % (app, file)

os.system(cmd)

Resulted cmd here is:

open -a '/Applications/MyApp/myAppExecutable' '/Users/userName/Pictures/myPicture.jpg'

and it runs just fine.

But the application I am running accepts an optional startup argument -proj filepath, so a full cmd string with this optional argument should look like:

open -a '/Applications/MyApp/myAppExecutable' -proj '/Users/userName/Pictures' '/Users/userName/Pictures/myPicture.jpg'

But if I feed os.system() with a such cmdstring I am getting:

open: invalid option -- p

How to pass an optional app argument without causing an error and crash?

Upvotes: 1

Views: 389

Answers (2)

alphanumeric
alphanumeric

Reputation: 19329

It is quite possible to submit the application's specific arguments to OS open command. The syntax to open:

open -a /path/to/application/executable.file /filepath/to/the/file/to/open/with/app.ext

It appears it is OK to enclose both paths in double or single quotes such as:

open -a '/path/to/application/executable.file' '/filepath/to/the/file/to/open/with/app.ext'

As Ned has mentioned flag --args can be used to specify any Application's specific startup flags. The App specific flags are placed after open's --args flag such as:

open -a /path/to/application/executable.file  --args -proj

The problem is that the App specific flags (such as -proj) will only be passed at the time the App is starting up. If it is already running the open -a command will only open a file (if the file_to_be_opened is specified) but won't deliver the App's specific args. By other words the App is only able to receive its args at the time it starts. There is -n flag available to be used with open -a command. When used open -a will start as many instances of Apps as needed. Each of App instances will get the App args properly.

open -a '/path/to/application/executable.file' '/filepath/to/the/file/to/open/with/app.ext -n --args -proj "SpecificToApp arg or command" '

It all translates if used with subprocess:

subprocess.check_call(['open', '-a', app, file, '-n', '--args', '-proj', 'proj_flag_values'])

or simply pass it as a string arg to:

os.system(cmdString)

Upvotes: 1

nneonneo
nneonneo

Reputation: 179392

Per the open man page, you have to pass --args before arguments to the program:

 --args
     All remaining arguments are passed to the opened application in the
     argv parameter to main().  These arguments are not opened or inter-
     preted by the open tool.

As an aside, you may want to look into using subprocess. Here's how the command looks like with subprocess:

subprocess.check_call(['open', '-a', app, file])

No fiddling with string interpolation required.

Upvotes: 1

Related Questions