2017-08-28 126 views
0
import os 
gsize = os.system('dir dir C:\Users\GNK\Documents') 

這將發出如下。但我只想打印最後2行。如何從命令提示符輸出中使用python打印特定行

C:\Users\GNK>dir C:\Users\GNK\Documents 
06/26/2017 04:24 PM   13,826 1.xlsx 
07/03/2017 10:52 PM   15,068 2.xlsx 
08/11/2017 05:59 PM   3,227,457 3.zip 
08/14/2017 02:56 PM    527 4.sql 
06/09/2017 02:36 PM    3,976 5.sql 
06/09/2017 02:54 PM   601,580 6.zip 
06/12/2017 07:59 PM  116,641,792 7.mp3 
08/12/2017 09:25 AM  15,747,576 8.exe 
06/16/2017 12:23 AM   286,829 9 
08/19/2017 02:38 PM   1,211,008 10 
07/21/2017 08:08 AM   98,776 11 
08/03/2017 10:38 PM  10,427,892 11 
06/04/2017 05:20 PM   196,126 12 
05/21/2017 09:11 AM   196,126 13 
06/04/2017 05:22 PM   232,964 14 
05/21/2017 09:11 AM   232,964 15 
07/07/2017 12:03 PM   13,077 16 
07/07/2017 12:02 PM   13,076 v17t 
07/06/2017 07:57 AM  49,400,720 18 
05/23/2017 12:56 AM   551,522 19 
      160 File(s) 921,950,736 bytes 
       3 Dir(s) 21,563,650,048 bytes free 

我只想打印最後2行。我怎樣才能做到這一點。請幫助

回答

1

os.system文檔,你可以閱讀:

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.

所以,我覺得這是更好地爲您做這樣的事情:

import subprocess 
print(subprocess.check_output(['dir', 'C:\Users\GNK\Documents']).splitlines()[-2:]) 

.splitlines()[-2:]部分是隻保留最後兩個線。你可以加入他們形成一個雙線字符串,如果你想:

str.join('\n', subprocess.check_output(['dir', 'C:\Users\GNK\Documents']).splitlines()[-2:]) 
+0

謝謝。我試過這是拋出一個錯誤。無法解決這個問題。請在下面找到該錯誤Traceback(最近調用最後一次): 文件「g_size.py」,第4行,在 proc1 = subprocess.Popen('git.cmd dir') 文件「C:\ Python27 \ lib \文件「C:\ Python27 \ lib \ subprocess.py」,行640,在_execute_child中 startupinfo) WindowsError:[錯誤2]系統找不到指定的文件 – GNK

+0

@GNK從哪裏運行腳本?我讀了你的錯誤輸出'git.cmd dir',請嘗試在你擁有的任何git shell之外運行腳本。另一個要嘗試的是將'shell = True'參數添加到'subprocess.check_output'函數。 –

+0

嘗試更改函數並在git cmd之外運行。仍然沒有運氣。錯誤如下。文件「g_size.py」,第4行,在 print(subprocess.check_output(['dir','C:\ Users \ gnk''shell = True']).lineslines()[ - 2:]) 文件「C:\ Python27 \ lib \ subprocess.py」,行212,在check_output process = Popen(stdout = PIPE,* popenargs,** kwargs) 文件「C:\ Python27 \ lib \ subprocess.py」,線390,在__init__ errread,ERRWRITE) 文件 「C:\ Python27 \ lib中\ subprocess.py」,線路640,在_execute_child STARTUPINFO) WindowsError:[錯誤2]系統無法找到該文件指定 – GNK

相關問題