I wonder how I get the result of a command in python that runs in CMD and save in a variable,

Asked

Viewed 883 times

2

That program drips a IP, would like to pick up the result of that ping that is done on this line

os.system ('ping -n 4 {} '.format(ip))

that opens the CMD and drips the IP, and save to any variable, so you can put it in a file .txt afterward.

import PySimpleGUI
import os

class Tela : 

    def __init__ (self) :
        layout = [
            [PySimpleGUI.Text ('ip'),PySimpleGUI.Input(key='ip')],
            [PySimpleGUI.Button('enviar')]
        ]
        janela = PySimpleGUI.Window('Dados').layout(layout)
        self.button, self.values = janela.Read()

    def iniciar (self):
        print (self.values)
        ip = self.values ['ip']
        os.system ('ping -n 4 {} '.format(ip))
        return '' 


tela1 = Tela()
tela1.iniciar ()
  • Could you clarify what you want to take and where you want to save?

  • 1

    This program drops an ip, I would like to take the result of this ping that is done on this line os.system ('ping -n 4 {} '.format(ip)), which opens the cmd and drops the ip, and save in any variable, to be able to put in a file . txt later.

  • you can just use os.popen() instead of os.system - and call the method read() in the return value of it. The new way of doing this, with subprocess.run (or worse, subprocess.Popen) which is in the answer complicates too many simple cases. Just put there in the iniciar: return os.popen(f'ping -n 4 {ip}').read() - (Unlike "subprocess", "f-strings" simplify, not having to put ". format" )

1 answer

2

If you want to get the return in the terminal of a system process call use the module subprocess that allows generating new processes connect to the input, output and error Pipes, and get their return codes.

import subprocess

google = 'www.google.com' 
ptSO = '151.101.129.69'
microsoft = '184.26.42.115'


def ping(site):
   #Abre um subprocesso ping usando a sintaxe Linux
   p = subprocess.run(['ping', '-c', '4', site], stdout=subprocess.PIPE)
   #Abre um subprocesso ping usando a sintaxe Windows
   #p = subprocess.run(['ping', '/n', '4', site], stdout=subprocess.PIPE)

   stdout = p.stdout #captura stdout

   #Retorna o texto do terminal se hover erro retorna vazio
   return stdout.decode('UTF-8') if p.returncode == 0 else ''
   #No windows 
   #return stdout.decode('ISO-8859-1') if p.returncode == 0 else ''

print('aguarde...')
# Salva o retorno de alguns pings em uma lista
pings = [ping(google), ping(ptSO), ping(microsoft)]

print('salvando no arquivo...')
# Salva o retorno de alguns pings em um arquivo
with open("pings.txt", "w") as arquivo:
  for p in pings: 
    arquivo.write(f'{p}\n')

print('despejando no console...')
#imprime a lista contento a saída no terminal de alguns pings
for p in pings: print(f'{p}\n')

Test the code in the Repl.it: https://repl.it/repls/SuburbanThoroughLightweightprocess

  • The following error occurs Unicodedecodeerror: 'ascii' codec can’t Decode byte 0xa1 in position 305: ordinal not in range(128)

  • only thing I want is to take this value that comes out and save in a . txt as if I typed in cmd ping www.google.com > sarvar_file.txt

  • please - use the subprocess.run and rewrite the answer. Putting "subprocess.Popen" as "standard substitude of everything" was one of the biggest errors of Python’s evolution in a period, since it transformed several very simple calls into the module os and made the Megazord subprocess.Popen that is much more complicated to use. To improve a little, they made the subprocess.run - which has several standard attributes and simplifies the results.

  • And can for an example using os.popen(...).read() also - wanting to complicate this too much was a mistake, and obviously has no advantages to compensate for this for simple cases.

  • Sorry, I couldn’t understand.

  • Why does the command os.system ('ping -n 4 {} '.format(ip) + ' > file.txt') not work? Does it have a path near this?

  • @jsbueno is not wanting to complicate but the module’s own documentation subprocess states that its existence is due to the claim to replace several older modules and functions by listing `` and os.system and os.spawn. In the PEP 324 states that the motivation of this module is to replace inappropriate functions to initiate processes that may pose a safety risk.

  • @Gabrielamorim if you look at the example, you will see that there is a commented line with Windows syntax: #p = subprocess.run(['ping', '/n', '4', site], stdout=subprocess.PIPE) as it seems to be using windows remove the previous line with the Linux syntax and use this syntax.

  • @Gabrielamorim see the edition I made in the reply.

  • The code that changed this error: Traceback (Most recent call last): , line 19, in <module> pings = [ping(google), ping(ptSO), ping(microsoft)] File "c:/Users/Gabriel Ramos Amorim/Documents/Programs/Asda/as.py", line 15, in ping Return stdout.Decode('UTF-8') if p.returncode == 0 Else ' Unicodedecode: 'utf-8' codec can’t Decode byte 0xa1 in position 305: invalid start byte

  • @Gabrielamorim I will test in windows

  • I did on Windows, it’s the OS I use. and gave this error

  • @Gabrielamorim Try this on: return stdout.decode('ISO-8859-1') if p.returncode == 0 else ''

  • @Augustovasques - yes, that’s why I told you to rewrite using subprocess.run which is a middle ground. And it was added, after a 6 or 7 to, which was a great m. to leave the documentation of the Popen prominent and the .run hidden - when this is much simpler and covers almost all use cases.

  • As for the "security issues", they refer to the injection of parameters into the shell, when what will be executed can be provided by program users, not by the programmer. There’s no point in a script to pick up ping.

  • 1

    good report, but question dup de https://answall.com/q/448074/3635 ... very little effort;o by the PA in reviewing the question.

  • @Augustovasques Got it, my man, thank you very much.

  • @Gabrielamorim if the answer helped him and there is no longer any doubt consider to mark as correct by clicking on the symbol beside.

Show 13 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.