Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

subprocess.run only accepting first argument

Using Python 3.10.6
trying to pass an argument to a command line opened via subprocess.run, I’ve tried toggling shell=True/False, as well as passing the second argument with the input variable, no luck. here is the relevant code:

cmds = (['cmd','echo hello'])
cmd_result = subprocess.run(cmds, shell=False, check=True,
                            stdin=subprocess.PIPE,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            universal_newlines=True )
print(cmd_result.args)

[‘cmd’, ‘echo hello’]

print(cmd_result.stdout)

Microsoft Windows [Version 10.0.19044.1889] (c) Microsoft Corporation.
All rights reserved.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

C:\Users\oakne\Desktop\DiscordBots>

So it seems to recognize both the arguments, its just not doing anything with the second one. Any guidance is appreciated

>Solution :

If you run the command

cmd echo hello

from the CMD prompt, you do not get an echoed output of hello.

To run a command string, you need to add either /C or /K. The first runs a command string and exits, the second runs a command string and stays open. Without either of these flags, the command string is ignored.

Instead, try:

cmd /C echo hello

Adding this to your subprocess command, you get:

cmds = (['cmd', '/C', 'echo', 'hello'])
cmd_result = subprocess.run(cmds, shell=False, check=True,
                            stdin=subprocess.PIPE,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            universal_newlines=True )
print(cmd_result.stdout)
# prints:
hello
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading