우분투 컴퓨터에서 "dpkg -l"명령 출력의 두 번째 열을 캡처하고 싶습니다. 파이썬 3을 사용하고 하위 프로세스 모듈을 사용하고 싶습니다. 다음 명령 :
fh=open("/tmp/test.out", 'wb')
with subprocess.Popen(["dpkg", "-l"], stdout=subprocess.PIPE) as proc:
fh.write(proc.stdout.read())
다음과 같이 반환됩니다.
ii yum 3.4.3-3 all Advanced front-end for rpm
ii zeitgeist-core 1.0-0ubuntu4 amd64 event logging framework - engine
ii zenity 3.24.0-1 amd64 Display graphical dialog boxes from shell scripts
ii zenity-common 3.24.0-1 all Display graphical dialog boxes from shell scripts
ii zip 3.0-11build1 amd64 Archiver for .zip files
ii zita-ajbridge 0.7.0-1 amd64 alsa to jack bridge
ii zita-at1 0.6.0-1 amd64 JACK autotuner
ii zita-lrx 0.1.0-3 amd64 Command line jack application providing crossover filters
ii zita-mu1 0.2.2-2 amd64 organise stereo monitoring for Jack Audio Connection Kit
.....
.....
두 번째 열을 얻고 싶습니다. 예 :
....
....
yum
zeitgeist-core
zenity
zenity-common
zip
....
.... etc etc
도와주세요
>>> with subprocess.Popen(["dpkg", "-l"], stdout=subprocess.PIPE) as proc:
... line1=proc.stdout.read()
... type(line1)
...
<class 'bytes'>
유형은 바이트입니다. 분할하는 방법. 다음을 사용할 때 :
>>> with subprocess.Popen(["dpkg", "-l"], stdout=subprocess.PIPE) as proc:
... line1=proc.stdout.read()
... line2=str(line) # the type is byte so I try to convert to string
... print(line2)
...
10
(출력이 엉망이 됨)
시스템 호출의 출력을 얻는 방법은 매우 구식입니다. 사용하다
subprocess.check_output()
대신 :
#!/usr/bin/env python3
import subprocess
f = "/home/jacob/Desktop/output.txt"
lines = subprocess.check_output(["dpkg", "-l"]).decode("utf-8").splitlines()
with open(f, "wt") as out:
for l in lines:
if l.startswith("ii"):
out.write(l.split()[1] + "\n")
f
출력 파일의 실제 경로로 바꿉니다 .
결과물 파일:
...
...
apg
app-install-data
app-install-data-partner
apparmor
apport
apport-gtk
apport-retrace
apport-symptoms
appstream
apt
apt-transport-https
...
...
위의 솔루션은 빈 줄로 끝나는 파일을 만듭니다. 이것이 문제라면 아래 해결책을 사용하십시오.
#!/usr/bin/env python3
import subprocess
f = "/home/jacob/Bureaublad/output.txt"
lines = subprocess.check_output(["dpkg", "-l"]).decode("utf-8").splitlines()
open(f, "wt").write(
"\n".join([l.split()[1] for l in lines if l.startswith("ii")])
)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다