Python 仅当另一个函数不返回None时才调用该函数
因此,我正在处理一个任务,它要求我处理两个单独的python文件,一个使用我的主代码,另一个使用两个函数,一个用于加密文件,另一个用于解密文件。这是主代码文件的外观:Python 仅当另一个函数不返回None时才调用该函数,python,python-3.x,function,exception-handling,Python,Python 3.x,Function,Exception Handling,因此,我正在处理一个任务,它要求我处理两个单独的python文件,一个使用我的主代码,另一个使用两个函数,一个用于加密文件,另一个用于解密文件。这是主代码文件的外观: import sys sys.path.append('C:\\Users\\gabri\\Desktop\\CS\\Assignment 7') from assgn7 import encrypt_file, decrypt_file file_in = 'Sample.txt' print('Encrypting in
import sys
sys.path.append('C:\\Users\\gabri\\Desktop\\CS\\Assignment 7')
from assgn7 import encrypt_file, decrypt_file
file_in = 'Sample.txt'
print('Encrypting input file', file_in)
enc_dict = encrypt_file(file_in)
print('-' * 20)
print('Decrypting input file', file_in)
decrypt_file(enc_dict, file_in + '.enc')
我应该修改此代码,以便仅当encrypt\u file()
未返回None
时调用decrypt\u file()
我该怎么办?我在考虑可能使用异常处理,但不知道这需要捕获什么样的错误 在
decrypt_file
中,如果enc_dict
为无,则可以终止函数
def decrypt_file(enc_dict, filein):
if enc_dict is None:
return
< rest of code >
def decrypt_文件(enc_dict,filein):
如果enc_dict为无:
返回
<代码的其余部分>
只需检查返回的对象即可
import sys
sys.path.append('C:\\Users\\gabri\\Desktop\\CS\\Assignment 7')
from assgn7 import encrypt_file, decrypt_file
file_in = 'Sample.txt'
print('Encrypting input file', file_in)
enc_dict = encrypt_file(file_in)
if enc_dict is not None:
print('-' * 20)
print('Decrypting input file', file_in)
decrypt_file(enc_dict, file_in + '.enc')
至于使用异常,您需要知道在这种情况下会引发什么异常
decrypt_file
。您可以查看它的文档,查看它的源代码,或者只尝试一次,看看会发生什么-最后一个不太健壮,但我会这么做。