如何用Python精确复刻Windows CMD的mkdir文件夹创建行为?
Great question! The discrepancy you're seeing boils down to how different tools interact with Windows' filesystem APIs. CMD's mkdir uses the raw Windows CreateDirectoryW API directly, which seems to trigger Google Drive's ignore filter correctly, while Python's os module functions might be routing through the C runtime with extra logic that bypasses this check.
Here are two reliable ways to replicate CMD's folder creation behavior in Python:
1. Use ctypes to Call Windows' Native CreateDirectoryW API
This method directly invokes the same low-level API that CMD uses, ensuring the folder is created with the exact attributes Google Drive expects to apply its ignore rule.
import ctypes from ctypes import wintypes # Load the Windows kernel32 library kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) # Define the function signature for CreateDirectoryW CreateDirectoryW = kernel32.CreateDirectoryW CreateDirectoryW.argtypes = [wintypes.LPCWSTR, wintypes.LPVOID] CreateDirectoryW.restype = wintypes.BOOL def mkdir_native(path): """Create a folder using Windows' native API, matching CMD's mkdir behavior""" # Convert path to wide string (required for Unicode Windows APIs) wide_path = ctypes.c_wchar_p(path) # Create folder with default security attributes success = CreateDirectoryW(wide_path, None) if not success: # Raise a meaningful error if creation fails error_code = ctypes.get_last_error() raise ctypes.WinError(error_code) return True # Example usage mkdir_native(".workspace")
2. Call CMD's mkdir Directly via subprocess
If you prefer a more straightforward (though slightly less efficient) approach, you can spawn a CMD process to run the mkdir command directly:
import subprocess def mkdir_via_cmd(path): """Create a folder by calling CMD's mkdir command""" # Use check=True to raise an error if mkdir fails subprocess.run( ["cmd.exe", "/c", "mkdir", path], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) # Example usage mkdir_via_cmd(".workspace")
Key Notes
- Testing: Before testing, delete any existing
.workspacefolders created via Python/Explorer first—Google Drive might already have indexed them and won't retroactively apply the ignore rule. - Path Handling: Both methods work with relative and absolute paths; use Windows-style backslashes (or raw strings like
r"C:\path\to\.workspace") to avoid path parsing issues. - Performance: The
ctypesmethod is faster since it doesn't spawn a new process, whilesubprocessis more readable but adds minor overhead.
Either approach should create the .workspace folder in a way that triggers Google Drive's ignore filter, just like using CMD's mkdir directly.
内容的提问来源于stack exchange,提问作者Ruslan Vasylev

