How to use subprocess

1

I do not know if there is any way to capture what comes out in the cmd, and tried to do this, it shows me the information but it does not generate the file and it throws me this error:

Traceback (most recent call last):
  File "comandos.py", line 5, in <module>
    datos=info.readlines()
AttributeError: 'CompletedProcess' object has no attribute 'readlines'

This is the code:

import subprocess 
comando=("ipconfig")
info=subprocess.run((comando),shell=True)
datos=info.readlines()
fichero=open("datos", "w")
fichero.writelines(info)
fichero.close()
print("El nombre del fichero es datos")
    
asked by Snake 24.09.2017 в 15:54
source

1 answer

0

You have to redirect standard output properly. If you only want to save it in a file you can redirect it directly

import subprocess


with open("datos.txt", 'wb') as f:
    subprocess.run(['ipconfig'], stdout=f, shell = True)

If you want to save it in a string to print it or anything else, you can redirect the output using pilelines

import subprocess


p = subprocess.run(['ipconfig'], stdout=subprocess.PIPE, shell = True)
out = p.stdout
print(out.decode("cp850"))
with open("datos.txt", 'wb') as f:
    f.write(out)

In Python > 3.6 you can define the appropriate encoding with the% encoding of subprocess.run , so it is possible to do

import subprocess

p = subprocess.run(['ipconfig'],
                   stdout=subprocess.PIPE,
                   shell = True,
                   universal_newlines = True,
                   encoding = "cp850")
out = p.stdout
print(out)
with open("datos.txt", 'w') as f:
    f.write(out)

universal_newlines=True uses the value returned by locale.getpreferredencoding(False) to encode the string. The problem is that Windows in this case works with the traditional DOS character maps, for Spanish it must be CP850 and not with the ones of applications such as CP1252.

We can save the output without problems using bytes and then read the file with the appropriate encoding. To print the file without problems if we need to specify the appropriate coding.

  

In the examples, "cp850" encoding is assumed by default for the terminal. Change if necessary. You can check, opening CMD and entering chcp .

Edit:

universal_newlines=True returns the output as text, regardless of the encoding to define the new line used ( \n in UNIX, \r\n in Windows, \r in OS up to version 9, etc). To do this, use the encoding returned by locale.getpreferredencoding(False) to decode the output. The problem is that this will not return the actual default CMD encoding which will be used to return the output of ipconfig . That is why it is advisable to avoid it and work directly with bytes.

stdout is the standard output (standard output) that as a general rule will be the console / terminal. In this case, roughly, redirect this output so that instead of the console is directed to a string or a file.

    
answered by 24.09.2017 / 16:34
source