Structuring main method


Structuring main method



I have a python script that will do 3 things, check to see if a file exists in a directory, copy specific files from one directory to another, and execute another python script. Right now if I run the script it runs through all 3 functions, regardless of if the file exists in the test directory.



What I want it to do is check to see if the file exists. If it does, copy it, and once it's copied execute the other script. I am having trouble figuring out a simple way to link them all together. Here is my script.


import os
import os.path
from os import path
import shutil


def check_file():
file_exists = False
for deploy_file in os.listdir("C:test1test.txt"):
if deploy_file.startswith("test"):
file_exists = True
else:
exit(1)
print file_exists


def copy_file():
src = "C:test1"
dst = "C:test2"

files = [i for i in os.listdir(src) if i.startswith("test") and path.isfile(path.join(src, i))]
print files
for f in files:
shutil.copy(path.join(src, f), dst)


def run_script():
os.system("pathofscript") # for testing its just a script that prints "hello world"


def main():
check_file()
copy_file()
run_script()


main()



So by running this as-is the output will be:


True
['test.txt']
"hello world"



How can I write my main() method to do what I am trying to do?





You need to use return statements to make these functions produce a programmatically useful result (print is not programmatically useful). Then you can use that result in the main method, e.g. controlling the other methods with if check_file():
– ShadowRanger
3 mins ago


return


print


if check_file():





Also, having check_file call exit(1) as the else case in the loop means your program would exit if any entry fails the test.
– ShadowRanger
2 mins ago


check_file


exit(1)


else




1 Answer
1



You can verify if the file exists with an if statement then run the other two functions. You will have to update check_file() to return True or False


check_file()


def check_file():
file_exists = False
for deploy_file in os.listdir("C:test1test.txt"):
if deploy_file.startswith("test"):
file_exists = True
else:
file_exists = False
return file_exists



Then you can use this as your main function


def main():
if check_file():
copy_file()
run_script()
else:
exit(1)






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

how to run turtle graphics in Colaboratory

Export result set on Dbeaver to CSV