這個程序的功能非常的簡單,就是每天在系統中新建一個文件夾。文件夾即當前的時間。此代碼是在同事那邊看到的,為了鍛煉下自己薄弱的Python能力,所以花時間重新寫了一個。具體代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import time,os basePath = & #039;F:\\work\\' thisYear = str (time.localtime()[ 0 ]) thisMonth = str (time.localtime()[ 1 ]) thisDay = time.strftime(" % Y - % m - % d", time.localtime()) yearPath = basePath + thisYear monthPath = basePath + thisYear + & #039;\\' +thisMonth dayPath = basePath + thisYear + & #039;\\' +thisMonth + '\\' + thisDay if not os.path.exists(yearPath): os.mkdir(yearPath) if not os.path.exists(monthPath): os.mkdir(monthPath) if not os.path.exists(dayPath): os.mkdir(dayPath) os.popen("explorer.exe" + " " + dayPath) os.popen("exit") |
剛開始寫的時候我使用的os.system()來調用windows程序,但發現每次執行是都會彈出一個python窗口,很是麻煩。問了下高人,說解決方案是把.py文件后綴改為.pyw后綴即可。但是試了下還是不行。在高人的指導下,才得知原來值需要將os.system()修改為os.popen()即可。
.py和.pyw有什么不同?
嚴格來說,它們之間的不同就只有一個:視窗運行它們的時候調用不同的執行檔案。視窗用python.exe 運行.py ,用pythonw.exe 運行.pyw 。這純粹是因為安裝視窗版Python 時,擴展名.py 自動被登記為用python.exe 運行的文件,而.pyw 則被登記為用pythonw.exe 運行。.py 和.pyw 之間的“其它差別”全都是python.exe 和pythonw.exe 之間的差別。
跟 python.exe 比較起來,pythonw.exe 有以下的不同:
- 執行時不會彈出控制臺窗口(也叫 DOS 窗口)
- 所有向原有的 stdout 和 stderr 的輸出都無效
- 所有從原有的 stdin 的讀取都只會得到 EOF
.pyw 格式是被設計來運行開發完成的純圖形界面程序的。純圖形界面程序的用戶不需要看到控制臺窗口。開發純圖形界面程序的時候,你可以暫時把.pyw 改成 .py ,以便運行時能調出控制臺窗口,看到所有錯誤信息。
os.system()和os.popen()有什么不同?
- os.system(command) 在一個子shell中運行command命令,并返回command命令執行完畢后的退出狀態。這實際上是使用C標準庫函數system()實現的。這個函數在執行command命令時需要重新打開一個終端,并且無法保存command命令的執行結果。
- os.popen(command,mode) 打開一個與command進程之間的管道。這個函數的返回值是一個文件對象,可以讀或者寫(由mode決定,mode默認是'r')。如果mode為'r',可以使用此函數的返回值調用read()來獲取command命令的執行結果。