Сценарий оболочки Macintosh Automator, запускающий anaconda «Нет модуля с именем «кодировки»»Python

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Сценарий оболочки Macintosh Automator, запускающий anaconda «Нет модуля с именем «кодировки»»

Сообщение Anonymous »

Я работаю над созданием способа щелкнуть правой кнопкой мыши по файлу .eml, использовать «быстрые действия», заставить Python извлекать из него два данных, вставлять два данных в новый файл xlsx и автоматически открывать файл xlsx. p>
Метод заключается в том, чтобы сценарий оболочки в Automator вызывал файл .py, который вызывает файл .ipynb.
Действие «Запустить сценарий оболочки» обнаружило ошибку ошибка: Когда Я запускаю его в файле .eml, который вижу: «/Applications/Xcode.app/Contents/Developer/usr/bin/python3: невозможно открыть файл '/users///Documents/run_notebook1.py': [Errno 1 ] Операция не разрешена»
Когда я использую автоматизатор для проверки сценария с «получением указанных элементов поиска»
The action “Run Shell Script” encountered an error: “Python path configuration:
PYTHONHOME = (not set)
PYTHONPATH = (not set)
program name = '/Users//opt/anaconda3/bin/python'
isolated = 0
environment = 1
user site = 1
import site = 1
sys._base_executable = '/Users//opt/anaconda3/bin/python'
sys.base_prefix = '/Users//opt/anaconda3'
sys.base_exec_prefix = '/Users//opt/anaconda3'
sys.platlibdir = 'lib'
sys.executable = '/Users//opt/anaconda3/bin/python'
sys.prefix = '/Users//opt/anaconda3'
sys.exec_prefix = '/Users//opt/anaconda3'
sys.path = [
'/Users//opt/anaconda3/lib/python39.zip',
'/Users//opt/anaconda3/lib/python3.9',
'/Users//opt/anaconda3/lib/python3.9/lib-dynload',
]
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
Python runtime state: core initialized
ModuleNotFoundError: No module named 'encodings'

>Current thread 0x00000001ef41cc00 (most recent call first):

Traceback (most recent call last):
File "/users//Documents/run_notebook1.py", line 27, in
run_notebook(eml_file)
File "/users//Documents/run_notebook1.py", line 16, in run_notebook
subprocess.run(command, shell=True,check=True)
File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/subprocess.py", line 528, in run
raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '/Users//opt/anaconda3/bin/jupyter nbconvert --to notebook --execute --inplace --ExecutePreprocessor.timeout=-1 /Users//Documents/process_email1.ipynb' returned non-zero exit status 1.


Я без проблем запустил файл .py в терминале, используя python3 file.py.
Shellscript в Automator (установлен xcode, поэтому мне не нужно указывать каталог Python):
python3 /users//Documents/run_notebook1.py "$1"

Файл .py:
import sys
import subprocess
import os

def run_notebook(eml_file):
# Path to the notebook
notebook_path = '/Users//Documents/process_email1.ipynb'

# Set environment variable
os.environ['EML_FILE_PATH'] = eml_file

# Command to run the notebook with nbconvert
command = f'/Users//opt/anaconda3/bin/jupyter nbconvert --to notebook --execute --inplace --ExecutePreprocessor.timeout=-1 {notebook_path}'

# Run the command
subprocess.run(command, shell=True,check=True)

# Ensure the file path is passed as argument
if len(sys.argv) != 2:
print("Usage: python run_notebook.py
")
sys.exit(1)

# Get the EML file path
eml_file = sys.argv[1]

# Run the notebook with the EML file path
run_notebook(eml_file)

Файл .ipynb
import email
import pandas as pd
import os
from email import policy
from email.parser import BytesParser
from datetime import datetime
import subprocess

# Retrieve the EML file path from the environment variable
eml_file = os.getenv('EML_FILE_PATH')

# Check if the environment variable is set
if not eml_file:
raise ValueError("EML_FILE_PATH environment variable not set. Please pass the file path.")

# Function to extract email file information
def extract_eml_info(eml_file):
# Parse the .eml file
with open(eml_file, 'rb') as f:
msg = BytesParser(policy=policy.default).parse(f)

# Extract the file name (without extension)
file_name = os.path.splitext(os.path.basename(eml_file))[0]

# Extract the most recent date of the email conversation
date_str = msg['date']
if date_str:
try:
email_date = email.utils.parsedate_to_datetime(date_str)
except Exception as e:
email_date = None
else:
email_date = None

return file_name, email_date

# Function to remove timezone information from DataFrame
def remove_timezone_from_df(df):
# Iterate over all columns
for col in df.columns:
if pd.api.types.is_datetime64_any_dtype(df[col]):
# Remove timezone info if it's a datetime column
df[col] = df[col].dt.tz_localize(None)
return df

# Function to process EML files
def process_eml_files(eml_files):
# List to store extracted data
data = []

for eml_file in eml_files:
file_name, email_date = extract_eml_info(eml_file)
data.append([file_name, email_date])

# Create DataFrame
df = pd.DataFrame(data, columns=['File Name', 'Most Recent Date'])
df = remove_timezone_from_df(df)

# Write to Excel
output_file = 'output_eml_data.xlsx'
df.to_excel(output_file, index=False, engine='openpyxl')
print(f"Data written to {output_file}")

# Open the newly created Excel file
if os.name == 'nt': # For Windows
os.startfile(output_file)
elif os.name == 'posix': # For macOS/Linux
subprocess.call(['open', output_file])

return output_file

# Process the provided EML file
process_eml_files([eml_file])


Подробнее здесь: https://stackoverflow.com/questions/793 ... -encodings
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»