0
from Decryptor.py import decryptor

userInput = int(input("What mode do you want to select? (1-4) "))

if userInput == 3:

    decryptor()

^this is the function that is executing as soon as the program is run regardless of whether the parameters for the if statement is met

#This code is from Decryptor.py
import os
from cryptography.fernet import Fernet

def decryptor():

    fileName = input("What is the name of the file you want to decrypt (case sensitive) ")

    with open(fileName+".key", "rb")as file:
        key = file.read()

    key = Fernet(key)

    with open(fileName+".json", "rb")as encryptedFile:
        passwordFile = encryptedFile.read()

    decrypt = key.decrypt(passwordFile)

    with open(fileName+".json", "wb")as decryptedFile:
        decryptedFile.write(decrypt)

    print("Your file has been decrypted.")

decryptor()

^and this is the function itself that is executing before anything else in the program

  • 1
    Because you _asked_ it to execute that function when your did `decryptor()` – Pranav Hosangadi Jul 24 '22 at 20:57
  • You are already calling the function decryptor below so it executes already. Suggestion would be to remove the last line ```decryptor()``` and it should work as expected – Abinav R Jul 24 '22 at 20:58
  • That is unclear what the problem is. If you write something different of `3` what happen ? – azro Jul 24 '22 at 20:58
  • When you import a module, all the top-level code in that module is _executed_. The module contains a call to `decryptor()` at the top level, so it is executed. – John Gordon Jul 24 '22 at 21:01
  • See https://stackoverflow.com/questions/419163/what-does-if-name-main-do – Thierry Lathuille Jul 24 '22 at 21:02

1 Answers1

2

The issue is that you call it in Decryptor.py

#This code is from Decryptor.py
import os
from cryptography.fernet import Fernet

def decryptor():
    fileName = input("What is the name of the file you want to decrypt (case sensitive) ")
    ...
    print("Your file has been decrypted.")

decryptor()  # << << << << << << << << << 

So when importing it the file from Decryptor, its code is executed and decryptor() called

azro
  • 53,056
  • 7
  • 34
  • 70
  • When I tried that though it gave me the error "ModuleNotFoundError: No module named 'Encryptor.py'; 'Encryptor' is not a package " –  Jul 24 '22 at 21:12
  • This is the first time you mention an Encryptor – Sören Jul 24 '22 at 21:26
  • @AdamWilson you don't use filename to import, remove `.py`, like Decryptor – azro Jul 25 '22 at 05:40