Cómo usar el Proceso.Start () o equivalente con Mono en un Mac y pasar argumentos


Estoy tratando de escribir algún código c # para iniciar un navegador usando Process.Start(app,args); donde apps es la ruta al navegador, por ejemplo, /Applications/Google Chrome.app/Contents/MacOS/Google Chrome y los args son --no-default-browser-check

Si lo hago, que funciona en Windows y en Linux

Process.Start("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","--no-first-run");

Consigo

open: unrecognized option `--no-first-run'
Usage: open [-e] [-t] [-f] [-W] [-n] [-g] [-h] [-b <bundle identifier>] [-a <application>] [filenames]
Help: Open opens files from a shell.
      By default, opens each file using the default application for that file.  
      If the file is in the form of a URL, the file will be opened as a URL.
Options: 
      -a                Opens with the specified application.
      -b                Opens with the specified application bundle identifier.
      -e                Opens with TextEdit.
      -t                Opens with default text editor.
      -f                Reads input from standard input and opens with TextEdit.
      -W, --wait-apps   Blocks until the used applications are closed (even if they were already running).
      -n, --new         Open a new instance of the application even if one is already running.
      -g, --background  Does not bring the application to the foreground.
      -h, --header      Searches header file locations for headers matching the given filenames, and opens them.

También he intentado Monobjc para intentar ejecutar el código con

// spin up the objective-c runtime
ObjectiveCRuntime.LoadFramework("Cocoa");
ObjectiveCRuntime.Initialize();
NSAutoreleasePool pool = new NSAutoreleasePool();

// Create our process
NSTask task = new NSTask();
NSPipe standardOut = new NSPipe();
task.StandardOutput = standardOut;
task.LaunchPath = @"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";

// add some arguments
NSString argumentString = new NSString("--no-first-run");
NSArray arguments = NSArray.ArrayWithObject(argumentString);
task.Arguments = arguments;

// We should have liftoff
task.Launch();


// Parse the output and display it to the console
NSData output = standardOut.FileHandleForReading.ReadDataToEndOfFile;
NSString outString = new NSString(output,NSStringEncoding.NSUTF8StringEncoding);
Console.WriteLine(outString);

// Dipose our objects, gotta love reference counting
pool.Release();

Pero cuando corro mi código usando NUnit hace que NUnit explote.

Sospecho que esto es un error, pero no puedo probarlo. Agradezco cualquier ayuda!

Author: AutomatedTester, 2010-02-13

4 answers

Para hacer el Proceso.Start use exec directly en lugar de usar el mecanismo del sistema operativo para abrir archivos, debe establecer UseShellExecute en false. Esto también es cierto en Linux y Windows.

Process.Start(new ProcessStartInfo (
    "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
    "--no-first-run")
    { UseShellExecute = false });

Tenga en cuenta que también puede utilizar 'abrir' para su caso de uso, para ejecutar el paquete de aplicaciones de Chrome correctamente. Use el argumento ' - a 'para forzarlo a ejecutar una aplicación específica, el argumento'- n 'para abrir una nueva instancia y' arg args ' para pasar argumentos:

Process.Start(new ProcessStartInfo (
    "open",
    "-a '/Applications/Google Chrome.app' -n --args --no-first-run")
    { UseShellExecute = false });
 21
Author: Mikayla Hutchinson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-19 20:14:32

Parece que Process usa la utilidad de línea de comandos open para iniciar.

Debe evitar llamar al ejecutable directamente. Si la aplicación ya se está ejecutando, esto iniciaría una segunda instancia de la misma en lugar de activar la instancia que ya se está ejecutando. Eso probablemente no es lo que quieres, y no todas las aplicaciones pueden manejar esto de todos modos.

Con open, la sintaxis para iniciar Chrome sería

open -a Chrome

No se como funciona la clase Process en macOS X, pero supongamos que los parámetros deben ser similares.

Tenga en cuenta que si solo desea abrir una página web, no debe especificar el ejecutable; en su lugar, simplemente pase la URL, para que se abra en el navegador predeterminado del usuario. Esto es válido para cualquier plataforma.

Process.Start("http://www.google.com");
 4
Author: oefe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-13 12:27:55

¿Ha intentado algo como concatenar los parámetros en el nombre del proceso en lugar de pasarlo separado?

var processName = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
var args = "--no-default-browser-check";
Process.Start(String.Format("{0} {1}", processName, args));
 1
Author: tucaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-13 11:27:58

¿Por qué no intentas algo como esto:

Process P = new Process();                        
P.StartInfo.FileName = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
P.StartInfo.Arguments = "--no-default-browser-check";
P.UseShellExecute = false;            
P.Start();
 1
Author: caesay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-15 14:47:41