2017-05-28 43 views
0

我想從使用os.system轉換成子下面蟒蛇 - 我不能使用os.system得到同樣的結果在子

os.system("egrep 'Invalid user' /home/bits/Desktop/Assessment/auth.log | cut -d ' ' -f 11 >tempfile.txt ") 

它的工作原理,但是當我寫使用子用同樣的語句會創建一個空文件,有些知道爲什麼以及如何解決這個問題? THX

a1=subprocess.Popen(["egrep \"Invalid users\" /home/bits/Desktop/Assessment/auth.log"],shell=True,stdout=subprocess.PIPE) ### instead of /home/bits/Desktop/Assessment/auth.log please modify with your full path of auth.log 
a2=subprocess.Popen(["cut -d \" \" -f 11 > /home/bits/Desktop/Assessment/rezolvare/tempfile.txt"],shell=True,stdin=a1.stdout,stdout=subprocess.PIPE) 
+0

你應該將stdout使用'stdout'參數文件。看看這個https://stackoverflow.com/questions/4856583/how-do-i-pipe-a-subprocess-call-to-a-text-file – gzc

+0

我修改它,但我有相同的結果:一個空文件a2 = subprocess.Popen([「cut -d \」\「-f 11」],shell = True,stdin = a1.stdout,stdout = open_file) – Bonfel

回答

0

你應該提供的輸出文件作爲stdout

with open("/home/bits/Desktop/Assessment/rezolvare/tempfile.txt", "wb") as output: 
    a1 = subprocess.Popen(["egrep", "Invalid users", "/home/bits/Desktop/Assessment/auth.log"], stdout=subprocess.PIPE) 
    a2 = subprocess.Popen(["cut", "-d", " ", "-f", "11"], stdin=a1.stdout, stdout=output) 

純Python編寫更簡單:

with open("/home/bits/Desktop/Assessment/auth.log") as lines: 
    with open("/home/bits/Desktop/Assessment/rezolvare/tempfile.txt", "wb") as output: 
     for line in lines: 
      if "Invalid users" in line: 
       output.write(line.split(" ")[10] + "\n") 
+0

Daniel,我嘗試了第一個和第二個,但我想我有這裏有個問題,我每次運行它時都會得到一個空文件?與os.system工程或與bash,但你得到它的方式不起作用,也許我在這裏有一個問題,你有它的答案?thx – Bonfel