Python脚本调用tempo2创建文件后重命名报错求助
Problem Description
I wrote a Python script that calls the astronomical command-line tool tempo2 to generate a file named polyco_new.dat, then tries to rename this file based on input file paths. However, I keep getting an error saying "polyco_new.dat does not exist (No such file or directory)", even though I've confirmed tempo2 is generating the file. Here's my script:
import os, sys import numpy as np with open('paths.txt', 'r') as paths_list: for file_path in paths_list: data = np.loadtxt(file_path.strip()) filename = file_path[-26:-5] # 创建'polyco_new.dat'文件 os.system("tempo2 -tempo1 -polyco \"%f %f 120 15 12 @ 0\" -f ephemerides.par" %(t0, te)) # 重命名文件 os.rename('polyco_new.dat', 'polycox_'+filename+'.dat')
Solution
Let's break down the issues and fix them step by step:
1. Core Issue: Working Directory Mismatch
tempo2 might be generating polyco_new.dat in a different working directory than where your Python script is looking for it. Even though os.system blocks until the command finishes, if tempo2 uses a different default directory (e.g., where ephemerides.par is located), your os.rename call will fail to find the file.
Fix this by using absolute paths for both the temporary file and the final renamed file:
current_dir = os.getcwd() temp_polyco_path = os.path.join(current_dir, 'polyco_new.dat')
2. Verify tempo2 Execution Success
Don't assume the command worked—check the exit code returned by os.system (a return value of 0 means success):
exit_code = os.system(f"tempo2 -tempo1 -polyco \"{t0} {te} 120 15 12 @ 0\" -f ephemerides.par") if exit_code != 0: print(f"tempo2 failed with exit code {exit_code} for file: {file_path}") continue
3. Fix Unstable Filename Extraction
Your file_path[-26:-5] is a fragile hardcode—if your file paths vary in length, this will produce garbage filenames. Use Python's os.path module to safely extract the filename:
# Get the filename without its extension filename = os.path.splitext(os.path.basename(file_path.strip()))[0]
4. Define Missing Variables
Your script uses t0 and te but doesn't define them—this will throw a NameError. I assume these values come from your loaded data array; adjust the extraction to match your actual data structure:
# Example: assuming t0 and te are the first two values in the data t0, te = data[0], data[1]
5. Add Robust Error Handling
Wrap your logic in try/except blocks to catch unexpected issues (like missing input files or corrupted data) and make your script more resilient.
Full Fixed Script
import os import numpy as np with open('paths.txt', 'r') as paths_list: current_dir = os.getcwd() temp_polyco = os.path.join(current_dir, 'polyco_new.dat') for file_path in paths_list: cleaned_path = file_path.strip() # Skip empty lines or non-existent files if not cleaned_path or not os.path.exists(cleaned_path): print(f"Skipping invalid/missing path: {cleaned_path}") continue try: # Load data and extract t0/te data = np.loadtxt(cleaned_path) t0, te = data[0], data[1] # Adjust this to match your data format # Extract safe filename filename = os.path.splitext(os.path.basename(cleaned_path))[0] # Run tempo2 and check success exit_code = os.system(f"tempo2 -tempo1 -polyco \"{t0} {te} 120 15 12 @ 0\" -f ephemerides.par") if exit_code != 0: print(f"Failed to generate polyco for {cleaned_path} (exit code: {exit_code})") continue # Check if temp file exists before renaming if os.path.exists(temp_polyco): final_path = os.path.join(current_dir, f'polycox_{filename}.dat') os.rename(temp_polyco, final_path) print(f"Successfully created: {final_path}") else: print(f"Error: {temp_polyco} not found after running tempo2 for {cleaned_path}") except Exception as e: print(f"Error processing {cleaned_path}: {str(e)}")
内容的提问来源于stack exchange,提问作者user90465

