Zapisuje wyjście podprocesu.Popen call in a string
Próbuję wykonać wywołanie systemowe w Pythonie i zapisać wyjście do ciągu znaków, który mogę manipulować w programie Pythona.
#!/usr/bin/python
import subprocess
p2 = subprocess.Popen("ntpq -p")
Wypróbowałem kilka rzeczy, w tym niektóre z sugestii tutaj:
Ale bez powodzenia.9 answers
W Pythonie 2.7 lub Pythonie 3
Zamiast tworzyć obiekt Popen
bezpośrednio, możesz użyć subprocess.check_output()
funkcja zapisująca wyjście polecenia w łańcuchu znaków:
from subprocess import check_output
out = check_output(["ntpq", "-p"])
W Pythonie 2.4-2.6
Użyj metody communicate
.
import subprocess
p = subprocess.Popen(["ntpq", "-p"], stdout=subprocess.PIPE)
out, err = p.communicate()
out
tego chcesz.
Ważna uwaga o innych odpowiedziach
Zauważ, jak przeszedłem w Komendzie. Przykład "ntpq -p"
przywołuje inną sprawę. Ponieważ Popen
nie wywołuje shell, można użyć listy poleceń i opcji-["ntpq", "-p"]
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-12 21:48:09
To działało dla mnie do przekierowania stdout (stderr może być obsługiwany podobnie):
from subprocess import Popen, PIPE
pipe = Popen(path, stdout=PIPE)
text = pipe.communicate()[0]
Jeśli to nie działa dla Ciebie, proszę dokładnie określić problem, który masz.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-03-23 19:12:58
Zakładając, że pwd
jest tylko przykładem, oto jak możesz to zrobić:
import subprocess
p = subprocess.Popen("pwd", stdout=subprocess.PIPE)
result = p.communicate()[0]
print result
Zobacz dokumentacja podprocesudla kolejny przykład i więcej informacji.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-03-23 19:19:21
Podproces.Popen: http://docs.python.org/2/library/subprocess.html#subprocess.Popen
import subprocess
command = "ntpq -p" # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None, shell=True)
#Launch the shell command:
output = process.communicate()
print output[0]
W konstruktorze Popen, Jeśli shell jest True , powinieneś przekazać polecenie jako ciąg znaków, a nie jako sekwencję. W przeciwnym razie po prostu podziel polecenie na listę:
command = ["ntpq", "-p"] # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None)
Jeśli chcesz również odczytać błąd standardowy, do inicjalizacji Popen, możesz ustawić stderrna podproces.PIPE lub do podprocesu .STDOUT :
import subprocess
command = "ntpq -p" # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
#Launch the shell command:
output, error = process.communicate()
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-28 19:14:19
To działa idealnie dla mnie:
import subprocess
try:
#prints results and merges stdout and std
result = subprocess.check_output("echo %USERNAME%", stderr=subprocess.STDOUT, shell=True)
print result
#causes error and merges stdout and stderr
result = subprocess.check_output("copy testfds", stderr=subprocess.STDOUT, shell=True)
except subprocess.CalledProcessError, ex: # error code <> 0
print "--------error------"
print ex.cmd
print ex.message
print ex.returncode
print ex.output # contains stdout and stderr together
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-11 20:10:51
Dla Pythona 2.7 + idiomatyczną odpowiedzią jest użycie subprocess.check_output()
Należy również zwrócić uwagę na obsługę argumentów podczas wywoływania podprocesu, ponieważ może to być nieco mylące....
Jeśli args jest pojedynczym poleceniem bez własnego args (lub masz shell=True
ustawione), może to być łańcuch znaków. W przeciwnym razie musi to być lista.
ls
, jest to w porządku:
from subprocess import check_call
check_call('ls')
Tak jest:
from subprocess import check_call
check_call(['ls',])
Jednakże, jeśli chcesz zdać niektóre args do polecenia powłoki, nie możesz zrobić tego:
from subprocess import check_call
check_call('ls -al')
Zamiast tego musisz podać go jako listę:
from subprocess import check_call
check_call(['ls', '-al'])
The shlex.split()
funkcja może być czasem przydatna do podzielenia łańcucha na składnię podobną do powłoki przed utworzeniem podprocesu...
tak:
from subprocess import check_call
import shlex
check_call(shlex.split('ls -al'))
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-08 02:38:33
To było dla mnie idealne. Otrzymasz kod zwrotu, stdout i stderr w krotce.
from subprocess import Popen, PIPE
def console(cmd):
p = Popen(cmd, shell=True, stdout=PIPE)
out, err = p.communicate()
return (p.returncode, out, err)
Na Przykład:
result = console('ls -l')
print 'returncode: %s' % result[0]
print 'output: %s' % result[1]
print 'error: %s' % result[2]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-05 10:38:21
import os
list = os.popen('pwd').read()
W tym przypadku będziesz miał tylko jeden element na liście.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-03-23 19:14:41
Napisałem małą funkcję na podstawie innych odpowiedzi tutaj:
def pexec(*args):
return subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0].rstrip()
Użycie:
changeset = pexec('hg','id','--id')
branch = pexec('hg','id','--branch')
revnum = pexec('hg','id','--num')
print('%s : %s (%s)' % (revnum, changeset, branch))
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-08 20:40:51