Search code examples
pythonwindowssubprocessdouble-quotes

Python subprocess appends double quote to last arg


It seems python subprocess.run appends one double quote to the last argument:

Python 3.9.4 (tags/v3.9.4:1f2e308, Apr  6 2021, 13:40:21) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> args = ['cmd', '/c', 'echo', 'hello']
>>> result = subprocess.run(args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> result.stdout
b'hello"\r\n'
>>> stdout = str(result.stdout, "utf-8").strip()
>>> stdout
'hello"'

I am using Windows 20H2 19042.928.

What am I doing wrong above?


Solution

  • Your args are already run in the default cmd or terminal (depending on your OS) when using subprocess.run(). So, you don't need the cmd arg. All you should need is;

    import subprocess
     
    args = ['echo', 'hello']
    result = subprocess.run(args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out = str(result.stdout, 'utf-8').strip()
    
    print(out)