0

My task is to connect my python code with the C++ code (called streamer) and then get the result back to python script. I have to send two parameters to the C++ code. The first one is just integer (no problem here), but the second one is a long string that you can see here.

8 0
37 0
81 0
95 0
116 0
133 0
145 0
184 0
207 0
223 0
258 0
277 0

In the C++ code, I am just printing both arguments using this code to see what I passed:

std::cout << "ARGUMENT 1: " << argv[1] <<'\n';
std::cout << "ARGUMENT 2: " << argv[2] <<'\n';

I tried several approaches that I've found here, but nothing works. When I try this python code it doesn't treat the second argument (long string) as one string but as multiple arguments.

p = subprocess.Popen([r'./Solver/solver.sh', str(3), long_string], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
solver_result, err = p.communicate()

print(solver_result)
print(err)

Another approach that I've tried is here. This time it just prints the first argument and that it crashes with error code 139 which is most likely because there is no argv[2]

p = subprocess.run([r'./Solver/solver.sh', str(3)], stdout=PIPE, input=long_string, encoding='ascii')
print(p.returncode)
print(p.stdout)

Shell script

#!/usr/bin/env bash

./Solver/streamer $1 $2 

What am I doing wrong?

3
  • What is the value of long_string? Commented Jun 11, 2019 at 19:09
  • Note that your script needs to quote its arguments to ensure they're passed through correctly. ./Solver/streamer "$1" "$2", or better, ./Solver/streamer "$@" to just pass them all through. Without the quotes, an empty string will disappear and not generate any arguments at all; a * will generate one argument per file in your current directory; two words will become one argument per word (with a default IFS), etc. Commented Jun 11, 2019 at 19:10
  • BTW, if you ran your code through shellcheck.net before asking here, it would have linked you to SC2086. Commented Jun 11, 2019 at 19:14

1 Answer 1

2

This is a bug in your shell script, not in your Python.

Quote your arguments to prevent them from being word-split, and then having each word separately processed as a glob:

#!/usr/bin/env bash
./Solver/streamer "$1" "$2"
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.