2017-08-28 127 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

相关问题