簡體   English   中英

如何將命令輸出存儲在文件中

[英]How to store command output in file

我需要將系統命令的輸出存儲在文本文件中。

例如:-

import os
os.system('ls -al')

它的輸出:

drwx------  2 root root  4096 Aug  7 12:08 .ssh
drwxr-xr-x  2 root root  4096 Feb 27  2021 Templates
-rw-r--r--  1 root root    63 Aug 11 20:29 txt
drwxr-xr-x  2 root root  4096 Oct 24 07:03 Videos
-rw-------  1 root root  6813 Jul 25 07:43 .viminfo
drwxr-xr-x  3 root root  4096 Mar  1  2021 .vscode
drwxr-xr-x  3 root root  4096 Aug  9 10:19 .wpscan
-rw-------  1 root root    98 Oct 24 16:13 .Xauthority
-rw-------  1 root root 27650 Oct 24 18:12 .xsession-errors
-rw-------  1 root root 40368 Oct 24 12:32 .xsession-errors.old
-rw-------  1 root root 24328 Oct 24 17:07 .zsh_history
-rw-r--r--  1 root root  8238 Feb 27  2021 .zshrc

我需要將此輸出數據存儲在文本文件中。 請幫我。

os.system("ls -al")不會返回您通常在 shell 中看到的輸出,而只會返回返回碼。 如果命令成功執行,則為0否則為1 ,等等。在此處閱讀更多相關信息。

但是您可以使用subprocess.check_output()來做到這一點。 請注意,命令必須作為命令/參數列表傳遞給方法:

import subprocess
output = subprocess.check_output(["ls", "-al"])
open("output.txt", "w").write(output)

您可以使用>將命令行輸出寫入文件,如下所示:

import os
os.system('ls -al > output.txt')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM