Skip to content
Advertisement

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.

C:UsersoakneDesktopDiscordBots>

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

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement