Reputation: 31
When i import one of my python scripts and run my current script , it seems to be running and displaying the output of the imported script which is really unusual behaviour. I have just imported this in my script but not really called any of its functions in my main code. How can i avoid from this behaviour happening ?
If i pass the -d flag with my main script it will run the usual code in my main script only
If i pass the -t flag with my main script , it will run the code from the imported python script only
main.py
import os
import argparse
import functions as funcs
import generate_json as gen_json
from test_compare_filesets import tester as imptd_tester
def get_json_location():
path = os.getcwd() + '/Testdata'
return path
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--export-date", action="store_true", required=True)
parser.add_argument("-t", "--execute-test", action="store_true", required=False)
args = parser.parse_args()
date = args.export_date
testt = args.execute_test
yml_directory = os.listdir('yaml/')
yml_directory.remove('export_config.yaml')
with open('dates/' + date + '.json', 'w') as start:
start.close()
for yml in yml_directory :
print("Running export for " + yml)
yml_file = os.path.join('yaml/' + yml)
json_path = get_json_location()
yml = funcs.read_config(yml_file)
data_folder = date
gen_json.generate_data_report(json_path , yml , data_folder)
if __name__ == '__main__':
main()
test_files.py
import generate_report as generate_reportt
def compare_filesets(file_names, previous_data, current_data):
for item in file_names:
print(item + generate_reportt.compare(previous_data.get(item), current_data.get(item)) + "\n")
def test_filesets():
'''
Test for scenario 1
'''
dict_1 = generate_reportt.read_file_into_dict("dates/2018-01-01.json")
dict_2 = generate_reportt.read_file_into_dict("dates/2018-01-02.json")
print(" Test 1 ")
compare_filesets(file_names=['a.json', 'b.json', 'c.json'],
previous_data=dict_1,
current_data=dict_2
)
Upvotes: 1
Views: 1419
Reputation: 932
This is why using the statement:
if __name__ == "__main__":
main()
is very important. You will want to add this to the script you're importing, and put all of your code that is being called within a main()
function in that script. The variable __name__
of a script changes depending on whether the script is imported or not. If you're not importing the script and running it, then that script's __name__
variable will be "__main__"
. However, if it is imported, the __name__
variable turns into the script's filename, and therefore everything in main()
function of that script will not be run.
For more information: What does if __name__ == "__main__": do?
Upvotes: 1