Python 子进程将双引号附加到最后一个 arg
Python subprocess appends double quote to last arg
似乎 python subprocess.run 在最后一个参数后附加了一个双引号:
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"'
我正在使用 Windows 20H2 19042.928。
我上面哪里做错了?
使用 subprocess.run() 时,您的参数已经 运行 在默认的 cmd 或终端中(取决于您的 OS)。所以,你不需要 cmd 参数。您只需要;
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)
似乎 python subprocess.run 在最后一个参数后附加了一个双引号:
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"'
我正在使用 Windows 20H2 19042.928。
我上面哪里做错了?
使用 subprocess.run() 时,您的参数已经 运行 在默认的 cmd 或终端中(取决于您的 OS)。所以,你不需要 cmd 参数。您只需要;
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)