看我這篇就夠了!os.system批量執行py文件!!!!


返回當前工作目錄的方式有很多,在此不一一列舉。

復制代碼下來還跑不通,相信大家已經有過這樣的經歷,下面貼一下百度排名前幾的代碼。

簡單意思就是遍歷目錄下的文件夾,尋找.py文件,拼接路徑,執行文件,整體看沒什么,實際情況呢,就是我親身測試在pycharm和vscode中都只能打開其他的py文件,根部不運行!!!!

1 import os
2 
3 D_list = os.listdir(os.getcwd())
4 
5 for file_name in D_list:
6     if os.path.isfile(file_name) and file_name.endswith('.py') and file_name.find("test1") == -1:  # 去掉test1.py文件
7         print(file_name)
8         os.system(os.path.join(os.getcwd(), file_name))

 

為什么??!!

很簡單,在cmd中我們要運行一個py文件需要輸入什么?

1 D:\Py_file>python test1.py
2 123456789

我們需要在cmd中的路徑后后面聲明這個文件是python的,我們只需要在執行路徑前加入“python”這個字就可以了

1 import os
2 
3 D_list = os.listdir(os.getcwd())
4 
5 for file_name in D_list:
6     if os.path.isfile(file_name) and file_name.endswith('.py') and file_name.find("execute_zhengwu") == -1:
7         os.system("python %s" % os.path.join(os.getcwd(), file_name))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM