Ejercicio
Listado De Archivos Ejecutables En Un Directorio
Objectivo
Desarrollar un programa Python que enumere todos los archivos ejecutables en un directorio específico. El programa debe escanear el directorio en busca de archivos con permisos ejecutables (por ejemplo, .exe, .sh, .bat u otros, según el sistema operativo) y mostrar sus nombres. Implementar el manejo de errores para gestionar los casos en los que el directorio no es válido o es inaccesible.
Ejemplo de ejercicio de Python
Mostrar código Python
import os
import stat
def is_executable(file_path):
"""Check if a file is executable."""
try:
# Check if the file has executable permissions
return os.access(file_path, os.X_OK)
except Exception as e:
print(f"Error checking permissions for {file_path}: {e}")
return False
def list_executable_files(directory):
"""List all executable files in a given directory."""
try:
# Check if the directory exists
if not os.path.isdir(directory):
print(f"Error: The directory '{directory}' does not exist or is not accessible.")
return
# List all files in the directory
all_items = os.listdir(directory)
executable_files = []
# Define common executable file extensions based on OS
executable_extensions = {
'.exe', '.bat', '.cmd', '.sh', '.bin', '.app'
}
# Scan through all files in the directory
for item in all_items:
item_path = os.path.join(directory, item)
# Check if it's a file and if it's executable
if os.path.isfile(item_path) and is_executable(item_path):
# For Unix-based systems, check the file extension too
if any(item.endswith(ext) for ext in executable_extensions):
executable_files.append(item)
# Display the executable files found
if executable_files:
print(f"\nExecutable files in '{directory}':")
for file in executable_files:
print(file)
else:
print(f"\nNo executable files found in '{directory}'.")
except PermissionError:
print(f"Error: Permission denied to access '{directory}'.")
except Exception as e:
print(f"Error: {e}")
def main():
"""Main function to interact with the user."""
# Get user input for the directory
directory = input("Enter the directory path: ")
# List the executable files in the directory
list_executable_files(directory)
# Run the program
if __name__ == "__main__":
main()
Output
Enter the directory path: /path/to/directory
Executable files in '/path/to/directory':
script.sh
program.exe
run.bat
Código de ejemplo copiado
Comparte este ejercicio de Python