How to import and call 'main' functions from different files - python

I have bunch of python script files that i've created, and running them one by one. how can call these script files and run methods one by one from a different script file. I need little help as method in each file is named main() and i'm not sure how to import and call this method by the same name.
file1.py
import sys
def main():
#do something
if __name__ == '__main__':
main()
file2.py
import sys
def main():
#do something else
if __name__ == '__main__':
main()

You can simply import them as modules, and call the main() function for each
import file1, file2
file1.main()
file2.main()

I think the following syntax will work for you:
from file1 import main as main1
from file2 import main as main2
...

if you want to import main from file1.py into file2.py, you can do from file1 import main as main1 or some other name. This way, you give an alias to the function name. Alternatively, import file1 and then call file1.main()

Related

Import error raised when importing file1.py in file2.py where file2.py also imports file1.py [duplicate]

This question already has answers here:
Circular dependency in Python
(5 answers)
Closed 3 years ago.
I my Python Pyramid files, File2.py is importing File1.py and File1.py is importing File2.py, which is creating an infinite loop and raising Import error. I need to import these to use the public varibles of the classes as well as therir functions. How do i achieve this ?
I tried below :
File2.py
Class File2 :
def __init__(self, sessionId):
from server.eventmanager.file1 import File1 # : Doesnt Work
if __name__ == "__main__":
from server.eventmanager.file2 import File2 # : Doesnt Work(Tried both(init+ main)/either
def myFunc(self):
print(File1.myvar)
File1.py
from /server/modules/mymodule/file2 import File2
Class File1:
def __init__(self):
pass
myvar = False
def updateMyVar(self,updatedvar):
cls.myvar=updatedvar
#Do Something
File "/server/eventmanager/file1.py", line 7, in <module>
from server.modules.mymodule.File2 import file2
File "/server/modules/mymodule/file2.py", line 13, in <module>
from server.eventmanager.File1 import file1
ImportError: cannot import name 'file1'
I think you are looking for cyclic dependency in python
Circular dependency in Pythonenter link description here
you can have look how to resolve them.
You can add above your first import an if clause.
If I understood you right then you start your code with File2.py.
In this case you should do it like that:
if __name__ == "__main__":
import file1
If you run File2.py __name__ will be __main__. As a result the if - clause is true and you import File1.py. Well now File1.py imports File2.py but this time __name__ isn't __main__ because it doesn't run as a "main-file". This time __name__ will be File1 and File1 doesn't import Test2 anymore because the if clause stops it, but it still has the code of it because it already imported it one time.
Edit:
Ok I got it! You have to put the if __name__ == "__main__" clause at the top of your code in your File1.py:
if __name__ == "__main__":
from server.eventmanager.file2 import file2 # Doesnt Work(Tried both(init+ main)/either
from server.eventmanager.file1 import File1 # : Doesnt Work
class File2:
def __init__(self, sessionId):
pass
def myFunc(self):
print(File1.myvar)

How to import a module for all others modules imported?

I have been trying to solve this problem for some hours without any success, I have a PHP background and it will work there but not with python
Let's suppose I have a file named Main.py:
import time
import myfunction
myfunction.Calculate()
And myfunction.py is something like:
def Calculate()
print('Thank you')
time.sleep(1)
When I run Main.py, it will crash saying 'time is not defined in my function', but it was defined even before importing my_function, why it does not work?
The simplest solution is to import time in your myfunction.py file. Import things where they are really used:
myfunction.py
import time
def Calculate()
print('Thank you')
time.sleep(1)
main.py
import myfunction
myfunction.Calculate()

if __name__ == '__main__' function call

I am trying to work around a problem I have encountered in a piece of code I need to build on. I have a python module that I need to be able to import and pass arguments that will then be parsed by the main module. What I have been given looks like this:
#main.py
if __name__ == '__main__'
sys.argv[] #pass arguments if given and whatnot
Do stuff...
What I need is to add a main() function that can take argument(s) and parse them and then pass them on like so:
#main.py with def main()
def main(args):
#parse args
return args
if __name__ == '__main__':
sys.argv[] #pass arguments if given and whatnot
main(sys.argv)
Do stuff...
To sum up: I need to import main.py and pass in arguments that are parsed by the main() function and then give the returned information to the if __name_ == '__main_' part.
EDIT
To clarify what I am doing
#hello_main.py
import main.py
print(main.main("Hello, main"))
ALSO I want to still be able to call main.py from shell via
$: python main.py "Hello, main"
Thus preserving the name == main
Is what I am asking even possible? I have been spending the better part of today researching this issue because I would like to, if at all possible, preserve the main.py module that I have been given.
Thanks,
dmg
Within a module file you can write if __name__ == "__main__" to get specific behaviour when calling that file directly, e.g. via shell:
#mymodule.py
import sys
def func(args):
return 2*args
#This only happens when mymodule.py is called directly:
if __name__ == "__main__":
double_args = func(sys.argv)
print("In mymodule:",double_args)
One can then still use the function when importing to another file:
#test.py
import mymodule
print("In test:",mymodule.func("test "))
Thus, calling python test.py will result in "In test: test test ", while calling python mymodule.py hello will result in "In mymodule: hello hello ".

Importing values in config.py

I wanted to mix a config.py approach and ConfigParser to set some default values in config.py which could be overridden by the user in its root folder:
import ConfigParser
import os
CACHE_FOLDER = 'cache'
CSV_FOLDER = 'csv'
def main():
cp = ConfigParser.ConfigParser()
cp.readfp(open('defaults.cfg'))
cp.read(os.path.expanduser('~/.python-tools.cfg'))
CACHE_FOLDER = cp.get('folders', 'cache_folder')
CSV_FOLDER = cp.get('folders', 'csv_folder')
if __name__ == '__main__':
main()
When running this module I can see the value of CACHE_FOLDER being changed. However when in another module I do the following:
import config
def main()
print config.CACHE_FOLDER
This will print the original value of the variable ('cache').
Am I doing something wrong ?
The main function in the code you show only gets run when that module is run as a script (due to the if __name__ == '__main__' block). If you want that turn run any time the module is loaded, you should get rid of that restriction. If there's extra code that actually does something useful in the main function, in addition to setting up the configuration, you might want to split that part out from the setup code:
def setup():
# the configuration stuff from main in the question
def main():
# other stuff to be done when run as a script
setup() # called unconditionally, so it will run if you import this module
if __name__ == "__main__":
main() # this is called only when the module is run as a script

How to run multiple test case from python nose test

I am a newbie in process of learning python and currently working on a automation project.
And i have N numbers of testcase which needs to be run on reading material people suggest me to use nosetest.
What is the way to run multiple testcase using nosetest?
And is the correct approach doing it:
import threading
import time
import logging
import GLOBAL
import os
from EPP import EPP
import Queue
import unittest
global EPP_Queue
from test1 import test1
from test2 import test2
logging.basicConfig(level=logging.DEBUG,
format='(%(threadName)-10s) %(message)s',
)
class all_test(threading.Thread,unittest.TestCase):
def cleanup():
if os.path.exists("/dev/epp_dev"):
os.unlink("/dev/epp_dev")
print "starts here"
server_ip ='192.168.10.15'
EppQueue = Queue.Queue(1)
EPP = threading.Thread(name='EPP', target=EPP,
args=('192.168.10.125',54321,'/dev/ttyS17',
EppQueue,))
EPP.setDaemon(True)
EPP.start()
time.sleep(5)
suite1 = unittest.TestLoader().loadTestsFromTestCase(test1)
suite2 = unittest.TestLoader().loadTestsFromTestCase(test2)
return unittest.TestSuite([suite1, suite2])
print "final"
raw_input("keyy")
def main():
unittest.main()
if __name__ == '__main__':
main()
Read
http://ivory.idyll.org/articles/nose-intro.html.
Download the package
http://darcs.idyll.org/~t/projects/nose-demo.tar.gz
Follow the instructions provided in the first link.
nosetest, when run from command line like 'nosetest' or 'nosetest-2.6' will recursively hunt for tests in the directory you execute it in.
So if you have a directory holding N tests, just execute it in that directory. They will all be executed.

Categories

Resources