I have a question about __ name __ = "__ main __" and command line arguments. So, I have a text file called "lab2_1.txt" and my main function "Lab2_1.py". I want two different outputs depending on the inputs which are command line arguments.
If only the text file "lab2_1.txt" is the input as a command line argument (one argument), I want the program to print:
[('Anna', 'Hello Everyone'), ('Kalle', 'Hi there'), ('Anna', 'Coffee break?',
('Pelle', 'Absolutely'), ('Kalle', 'Sure'), ('Anna', 'Great, see you downstairs in 5
minutes')]
But if I have two arguments which are the main program "Lab2_1.py" and the text file "lab2_1.txt", I want to send the text file to a function called "read_file" which will read the text file and return tuples containing the person's name and the respective message, like in the code above. This function works.
After the tuples are created and returned from the function "read_file", I want the user to be able to search for a name and only print the messages that the specific person wrote, for example, if you search for Anna, the output is:
[Anna] --> Hello Everyone
[Anna] --> Coffee break?
[Anna] --> Great, see you downstairs in 5 minutes
I've created a function called display_entry for this output and it should work, it looks like this:
def display_entry(name,message):
for msg in message:
if msg[0] == name:
print(f'[{name}] --> {msg[1]}')
My teacher wants me to use the __ name __ ="__ main __" function but I just don't get how it works... This is my def (main) code:
def main():
if len(sys.argv) == 3:
if 'Lab2_1.py' in sys.argv and 'lab2_1.txt' in sys.argv:
messages = read_file(sys.argv[2])
name1 = input('Enter a name to search for: \n')
display_entry(name1, messages)
if __name__ == "__main__":
main()
else:
filename = sys.argv[1]
orig_sys = sys.stdout
with open(filename,'w') as out:
sys.stdout = out
print(out)
I have imported sys in the beginning of the code. The function that creates tuples, read_file, is not included in this question but it works so that's why I don't insert it here.
So the else statement in the last code block is connected to when the only argument is the text file in the command line and if the command line includes two arguments, the main program and the text file, it should run the main() function.
Hopefully this makes sense and someone can help me! :) Thanks!
Aucun commentaire:
Enregistrer un commentaire