如何通过Python命令行读取pickle文件?自定义双文件加载代码是否可行?
Hey there! Let's tackle your two questions about working with pickle files in Python, step by step.
You can easily read a pickle file from the command line by combining command-line arguments (using sys.argv) and Python's built-in pickle module. Here's a straightforward example:
import sys import pickle def load_pickle(file_path): with open(file_path, 'rb') as f: return pickle.load(f) if __name__ == "__main__": # Check if the user provided the correct number of arguments if len(sys.argv) != 2: print("Usage: python your_script.py <path_to_pickle_file>") sys.exit(1) # Load the pickle data data = load_pickle(sys.argv[1]) print("Pickle file loaded successfully!") # Add your logic to use the loaded data here
To run this, just execute this command in your terminal:python your_script.py your_pickle_file.pkl
First, let's recap your original code:
import sys
import pickle
filename1 = sys.argv(1)
filename2 = sys.argv(2)
def read_file(filename1,filename2):
with open(filename1, 'rb') as file1:
file1=pickle.load()
with open(filename1, 'rb') as file2:
file2=pickle.load()
return file1
return file2
sys.exit()
Unfortunately, this code has several key issues that will prevent it from working correctly:
- Syntax error:
sys.argvis a list, so you need to use square brackets[](not parentheses()) to access elements. Sosys.argv(1)should besys.argv[1]. - Missing file object in
pickle.load(): Thepickle.load()function requires you to pass the opened file object as an argument (e.g.,pickle.load(file1)instead of justpickle.load()). - Duplicate file path: You're opening
filename1twice instead of usingfilename2for the second file. - Unreachable return statement: After
return file1, the function exits immediately, soreturn file2will never run. You should return both values as a tuple instead. - Function never called: You define the
read_filefunction but never invoke it with your filenames. - Premature
sys.exit(): This line terminates the script right after defining the function, so none of the loading logic runs.
Here's the fixed version of your code:
import sys import pickle def read_files(filename1, filename2): # Load the first pickle file with open(filename1, 'rb') as file1: data1 = pickle.load(file1) # Load the second pickle file with open(filename2, 'rb') as file2: data2 = pickle.load(file2) # Return both datasets as a tuple return data1, data2 if __name__ == "__main__": # Validate the number of command-line arguments if len(sys.argv) != 3: print("Usage: python your_script.py <path_to_first_pickle> <path_to_second_pickle>") sys.exit(1) # Get filenames from command-line arguments filename1 = sys.argv[1] filename2 = sys.argv[2] # Load the files and unpack the results data1, data2 = read_files(filename1, filename2) print("Both pickle files loaded successfully!") # Now you can work with data1 and data2 as needed
To run this corrected script, use:python your_script.py file1.pkl file2.pkl
内容的提问来源于stack exchange,提问作者miastone

