2

Have been trying to get something like this to work for a while, the below doesn't seem to be sending the correct arg to the c program arg_count, which outputs argc = 1. When I'm pretty sure I would like it to be 2. ./arg_count -arg from the shell outputs 2...

I have tried with another arg (so it would output 3 in the shell) and it still outputs 1 when calling via subprocess.

import subprocess
pipe = subprocess.Popen(["./args/Release/arg_count", "-arg"], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = pipe.communicate()
result = out.decode()
print "Result : ",result
print "Error : ",err

Any idea where im falling over? I'm running linux btw.

2 Answers 2

5

From the documentation:

The shell argument (which defaults to False) specifies whether to use the shell as the program to execute. If shell is True, it is recommended to pass args as a string rather than as a sequence.

Thus,

pipe = subprocess.Popen("./args/Release/arg_count -arg", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

should give you what you want.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, this does seem to fix the argument issue, but now I get no output whatsoever...
for whatever reason, the script has to be in the same directory as the executable to get a valid result? or i dont know how to write a filepath...
That shouldn't have to be the case; I can easily put my version of arg_count (in this case a 2-line Python script) in a different directory and get the correct result. Unless your arg_count itself has some awkward problem.
Wasn't getting errors with arguments with out options used as a sequence, but when options paired with args (-arg option) the targeted process couldn't assign the option to the corresponding arguments (in my case 'Missing argument for option x') Used your solution and passed args as a string fixed the issue
2

If shell=True then your call is equivalent to:

from subprocess import Popen, PIPE

proc = Popen(['/bin/sh', '-c', "./args/Release/arg_count", "-arg"],
             stdout=PIPE, stderr=PIPE)

i.e., -arg is passed to the shell itself and not your program. Drop shell=True to pass -arg to the program:

proc = Popen(["./args/Release/arg_count", "-arg"],
             stdout=PIPE, stderr=PIPE)

If you don't need to capture stderr separately from stdout then you could use check_output():

from subprocess import check_output, STDOUT

output = check_output(["./args/Release/arg_count", "-arg"]) # or
output_and_errors = check_output(["./args/Release/arg_count", "-arg"],
                                 stderr=STDOUT)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.