Risposte:
Ci sono diversi modi per farlo:
Un modo semplice è usare il modulo os:
import os
os.system("ls -l")
Cose più complesse possono essere ottenute con il modulo sottoprocesso: ad esempio:
import subprocess
test = subprocess.Popen(["ping","-W","2","-c", "1", "192.168.1.70"], stdout=subprocess.PIPE)
output = test.communicate()[0]
os.system("nslookup gmail.com")restituisce solo l'ultima riga 0, ma voglio ottenere la risposta completa.
Preferisco l'utilizzo del modulo sottoprocesso:
from subprocess import call
call(["ls", "-l"])
Il motivo è che se vuoi passare qualche variabile nello script questo offre un modo molto semplice per esempio prendere la seguente parte del codice
abc = a.c
call(["vim", abc])
call(["eog", "1breeproposal.png", "-f"])
In effetti, qualsiasi domanda sul sottoprocesso sarà una buona lettura
Dovresti anche esaminare commands.getstatusoutput
Questo restituisce una tupla di lunghezza 2 .. Il primo è il numero intero di ritorno (0 - quando i comandi hanno successo), il secondo è l'intero output come verrà mostrato nel terminale.
Per ls
import commands
s=commands.getstatusoutput('ls')
print s
>> (0, 'file_1\nfile_2\nfile_3')
s[1].split("\n")
>> ['file_1', 'file_2', 'file_3']
import os
os.system("echo 'hello world'")
Questo dovrebbe funzionare. Non so come stampare l'output nella shell python.
L'os.popen () è abbastanza semplice da usare, ma è stato sconsigliato dal Python 2.6. Dovresti usare il sottoprocesso modulo .
Leggi qui: leggere un os.popen (comando) in una stringa
In un quaderno jupyter puoi usare la funzione magica !
!echo "execute a command"
files = !ls -a /data/dir/ #get the output into a variable
Per eseguirlo come uno .pyscript dovresti usareipython
files = get_ipython().getoutput('ls -a /data/dir/')
eseguire lo script
$ ipython my_script.py
Puoi importare il modulo 'os' e usarlo in questo modo:
import os
os.system('#DesiredAction')
per python3 usa subprocess
import subprocess
s = subprocess.getstatusoutput(f'ps -ef | grep python3')
print(s)