Parsing argv with spaces to Python script from C++

90 Views Asked by At

I have a few Python scripts to deal with json object received from some API from the internet. Now, my main app is written in C++ (its for GUI and for my API key protection). I takes 2 inputs from the user. The one of them is a nickname and it can have spaces. Now, when I pass them in args to c++ program (now its only written as a console app) it works when I just use "", but then:

W:\src>XD "nickname with spaces" summoner_by_name
nickname with spaces
summoner_by_name
python main.py API_KEY nickname with spaces summoner_by_name

ARGV:
main.py
API_KEY
nickname
with
spaces
summoner_by_name
END OF ARGV

So the first part is a part of this code:

int main(int argc, char** argv){
    std::string name = argv[1];
    std::string command = argv[2];
    std::cout << name << std::endl;
    std::cout << command << std::endl;
    std::cout << python + API_KEY + " " + name + " " + command << std::endl;
    system((python + API_KEY + " " + name + " " + command).c_str());
    return 0;
}

And the second part is a part of this code:

def main(argv):
    API_KEY = argv[1]
    NAME = argv[2]
    print("ARGV:")
    for i in argv:
        print(i)
    print("END OF ARGV")

So it seems like C++ passes the 2 values without "" and that's why it's not working (I tried to pass it myself in cmdline with quotes - it worked). It works on Linux though. How can I pass those values with spaces?

1

There are 1 best solutions below

0
On BEST ANSWER

You likely need to quote the string yourself when constructing the command line for the system call:

system((python + API_KEY + " \"" + name + "\" " + command).c_str());