1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
|
import sys
import subprocess
from pathlib import Path
import os
import random
import logging # Import the logging module
from datetime import datetime # Import datetime to get timestamps
# Modify run_command to accept and use a logger
def run_command(cmd_list, step_name, logger):
"""Runs a command, logs details, and returns success status and result."""
cmd_str = ' '.join(cmd_list)
logger.info(f"--- Running step: {step_name} ---")
logger.info(f"Command: {cmd_str}")
try:
# Use encoding='utf-8' for text=True for broader compatibility
result = subprocess.run(cmd_list, check=True, capture_output=True, text=True, encoding='utf-8', errors='replace')
# Log STDOUT and STDERR if they exist
stdout = result.stdout.strip()
stderr = result.stderr.strip()
if stdout:
logger.info(f"STDOUT:\n{stdout}")
if stderr:
logger.warning(f"STDERR:\n{stderr}") # Log stderr as warning even on success
logger.info(f"Success: Step '{step_name}' completed.")
return True, result
except FileNotFoundError:
logger.error(f"Error during {step_name}: Command not found: {cmd_list[0]}. Is it installed and in PATH?")
return False, None
except subprocess.CalledProcessError as e:
logger.error(f"Error during {step_name}: Command returned non-zero exit status {e.returncode}.")
logger.error(f"Command: {cmd_str}") # Log the command string again for context
# Log captured output from the exception object
stdout_err = e.stdout.strip() if e.stdout else "N/A"
stderr_err = e.stderr.strip() if e.stderr else "N/A"
logger.error(f"STDOUT on error:\n{stdout_err}")
logger.error(f"STDERR on error:\n{stderr_err}")
return False, None
except Exception as e:
logger.error(f"An unexpected error occurred during {step_name}: {e}", exc_info=True) # exc_info=True adds traceback
return False, None
def setup_logging(log_dir, user, base_filename):
"""Configures logging to file and console."""
now = datetime.now()
timestamp = now.strftime("%Y%m%d_%H%M%S")
log_filename = f"{user}_{base_filename}_{timestamp}.log"
log_filepath = Path(log_dir) / log_filename
# Create logger
logger = logging.getLogger('script_logger')
logger.setLevel(logging.INFO) # Set the minimum level to log
# Prevent propagation to root logger if handlers are added multiple times
if logger.hasHandlers():
logger.handlers.clear()
# Create formatter
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
# Create File Handler
try:
file_handler = logging.FileHandler(log_filepath, encoding='utf-8')
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
except Exception as e:
print(f"T^T")
# Fallback or exit if logging is critical
# For now, we'll continue with console logging if possible
# Create Console Handler
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO) # You might want DEBUG for console, INFO for file
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
logger.info(f"Logging initialized. Log file: {log_filepath}")
return logger, log_filepath # Return the logger and the log file path
def main():
if len(sys.argv) < 3: # Updated check for 3 arguments
print("Usage: python your_script.py <user> <path_to_cpp_file>")
sys.exit(1)
user = sys.argv[1]
input_cpp_path_str = sys.argv[2]
input_cpp_path = Path(input_cpp_path_str)
# --- Basic path setup ---
if not input_cpp_path.is_file():
# Logging isn't set up yet, so use print for this critical early error
print(f"Error: Input file not found: {input_cpp_path}")
sys.exit(1)
directory = input_cpp_path.parent
stem = input_cpp_path.stem
ps_path = directory / f"{stem}.ps"
pdf_path = directory / f"{stem}.pdf"
# --- Setup Logging ---
# Pass directory, user, and file stem to setup_logging
logger, log_filepath = setup_logging(directory, user, stem)
logger.info(f"--- Script Start ---")
logger.info(f"User: {user}")
logger.info(f"Input C++ file: {input_cpp_path}")
logger.info(f"Output PS path (intermediate): {ps_path}")
logger.info(f"Output PDF path: {pdf_path}")
# --- Enscript Conversion ---
enscript_cmd = [
'enscript',
'-b', user, # Header text (user name)
# '-a', '0-10', # Page range (commented out, process all pages by default)
'-f', 'Courier9', # Font
'-o', str(ps_path), # Output PostScript file path
str(input_cpp_path) # Input C++ file path
]
# Use the logger in run_command
success, _ = run_command(enscript_cmd, "enscript conversion to PS", logger)
if not success:
logger.error("enscript command failed. Exiting.")
sys.exit(1)
# --- ps2pdf Conversion ---
ps2pdf_cmd = [
'ps2pdf',
str(ps_path),
str(pdf_path)
]
success, _ = run_command(ps2pdf_cmd, "ps2pdf conversion to PDF", logger)
if not success:
logger.error("ps2pdf command failed. Exiting.")
sys.exit(1)
# --- Cleanup Intermediate File ---
try:
logger.info(f"Attempting to clean up intermediate file: {ps_path}")
ps_path.unlink()
logger.info("Success: Cleaned up .ps file.")
except OSError as e:
logger.warning(f"Could not remove intermediate file {ps_path}: {e}")
# --- Prepare and Run Curl Upload ---
# Using the random choice as in your original modification, but currently only one IP
ip_addresses = ['10.12.13.27',"10.12.13.29","10.12.13.209","10.12.13.107"] # Add more IPs here if needed for real randomness
chosen_ip = random.choice(ip_addresses)
curl_url = f'http://{chosen_ip}:12306/'
logger.info(f"Selected target URL for upload: {curl_url}")
curl_cmd = [
'curl',
'-X', 'POST',
'-H', 'Content-Type: application/octet-stream',
'--data-binary', f'@{pdf_path}', # Use @ to read file content
curl_url
]
success, result = run_command(curl_cmd, "curl PDF upload", logger)
if not success:
logger.error("curl command failed. Exiting.")
sys.exit(1)
logger.info("--- Process Completed Successfully ---")
# Log the final server response if available
if result and result.stdout:
final_response = result.stdout.strip()
logger.info(f"Server response from {curl_url}:\n{final_response}")
else:
logger.info(f"No specific response body received from server at {curl_url}.")
if __name__ == "__main__":
main()
|