subprocess.run() produces different results than manual input… here is a solution to the problem.
subprocess.run() produces different results than manual input
I’m trying to run the following Windows console command via a Python script:
C:\My\Path\openssl.exe x509 -in C:\My\PEM\mypem.pem -noout -subject > C:\My\Data\data.txt
If you drop it directly into the console, the expected 1KB file is generated.
Using subprocess.run()
does not. It generates a file, but a 0KB file, as if it didn’t grab the stdout
response.
I tried without success :
# produces b''
args = 'C:/My/Path/openssl.exe x509 -in C:/My/PEM/mypem.pem -noout -subject'
data = subprocess.check_output(args)
print (data)
# produces b''
result = subprocess. Popen('C:/My/Path/openssl.exe x509 -in C:/My/PEM/mypem.pem -noout -subject', stdout = subprocess. PIPE)
print (result.stdout)
# produces a 0KB data.txt
# probably also producing a b'' thus the 0KB
subprocess.run('C:/My/Path/openssl.exe x509 -in C:/My/PEM/mypem.pem -noout -subject > C:/My/Data/data.txt')
Solution
If you want to parse the string into a command with parameters, you need to use shell=True
.
result = subprocess. Popen('C:/My/Path/openssl.exe x509 -in C:/My/PEM/mypem.pem -noout -subject', stdout = subprocess. PIPE, shell=True)
print(result.stdout)
Alternatively, you can specify the command as a list:
result = subprocess. Popen(['C:/My/Path/openssl.exe', 'x509', '-in', 'C:/My/PEM/mypem.pem', '-noout', '-subject'], stdout = subprocess. PIPE)