Help: exec.Command with arguments

I am using golang “os/exec” to call a Windows program with parameters.

If you call the program with

app.exe /param1:"0 1 2"

it returns ok

if you call the program with

app.exe "/param1:0 1 2"

it returns error

My problem is that I can’t use exec.Command to call the app correctly.

I have written a sample c# program.

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Environment.CommandLine);
            if (Environment.CommandLine.EndsWith("/param1:\"0 1 2\""))
            {
                Console.WriteLine("argument is valid");
            }
            else
            {
                Console.WriteLine("argument is invalid");
            }
            return;
        }
    }
}

here is my go code:

package main

import (
	"fmt"
	"os/exec"
)

func main() {
	arg1 := `/param1:"0 1 2"`
	fmt.Println(arg1)
	data, err := exec.Command("./ConsoleApp1.exe", arg1).Output()
	if err != nil {
		panic(err)
	}
	fmt.Println(string(data))

	arg1 = `"/param1:0 1 2"`
	fmt.Println(arg1)
	data, err = exec.Command("./ConsoleApp1.exe", arg1).Output()
	if err != nil {
		panic(err)
	}
	fmt.Println(string(data))

	arg1 = `/param1:0 1 2`
	fmt.Println(arg1)
	data, err = exec.Command("./ConsoleApp1.exe", arg1).Output()
	if err != nil {
		panic(err)
	}
	fmt.Println(string(data))
	return
}

Output is:

/param1:"0 1 2"
./ConsoleApp1.exe "/param1:\"0 1 2\""
argument is invalid

"/param1:0 1 2"
./ConsoleApp1.exe "\"/param1:0 1 2\""
argument is invalid

/param1:0 1 2
./ConsoleApp1.exe "/param1:0 1 2"
argument is invalid

Anyone can help me? Thanks.

It seems that I have to wrap a bat file, and call the bat file using os/exec.

Hi. In the c# program could you instead use Environment.GetCommandLineArgs() and if think you will get the arguments without extra quotes.

It’s just a sample C# program.

I want to call another program written by others (downloaded from Internet).

I see. And that program uses Environment.CommandLine instead of Environment.GetCommandLineArgs to read arguments?

That program is written in C++.

I think that program uses something like Environment.CommandLine.

my test(windows command line):

// ok
app.exe /param1:"0 1 2"
// error
app.exe "/param1:0 1 2"
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.