簡體   English   中英

os.system不會將結果寫入輸出文件

[英]os.system does not write the result to output file

我正在編寫這段代碼:

import os
os.system("start /wait cmd /c dir/s *.exe > Allexe1.txt")

應該執行的操作是獲取所有exe文件並將結果寫入該文件。 但是我得到一個空文件。

注意:我已經嘗試了相同的子過程,但總是收到錯誤Error [2]:找不到文件我正在使用Windows 7和python2.7

任何幫助表示贊賞。

您應該可以通過這種更改來完成此操作,因為通過os.system執行命令不需要start /wait cmd /c

import os
os.system("dir/s *.exe > Allexe1.txt")

但是,如果您要將其移至非Windows平台,則此代碼不是可移植的代碼。

如果您希望以更便攜的方式進行操作,建議您閱讀此問題/答案

import sys,os

root = "/home/patate/directory/"

for path, subdirs, files in os.walk(root):
    for name in files:
        # filter for files with an exe extension here
        print os.path.join(path, name)

您不應以這種方式枚舉Python中的文件。 而是使用隨附的glob模塊:

import glob
for filename in glob.glob('*.exe'):
    print filename

或者,因為你似乎想所有子目錄,使用os.walk()聯合fnmatch中所提到的glob文檔。 無論如何,您都不應為此付出代價。

https://docs.python.org/2/library/glob.html

嘗試這個

 import os

 result = os.popen("start /wait cmd /c dir/s *.exe > Allexe1.txt").read()
 if result is not None:
     #this is your object with all your results
     #you can write to a file
     with open('output.txt', 'w') as f:
         f.write(result)
 #you can also print the result to console.
     print result
 else:
     print "Command returned nothing"

暫無
暫無

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

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