how to use module = __import__(filename) and invoke the main function - python

I am trying to develop this program , that invokes the main function of another program and takes the program to be inkoved's name as user input , let us call this program 1 :
Program 1 # takes the program 2's name as user input
try:
print "Please input the file you want to test"
filename = raw_input().split(".")[0]
module = __import__(filename)
except:
program 2 is like
def main():
first()
def first():
5/0
if __name__ == "__main__":
main()
so basically I want to know how to invoke program 2's main function from program 1 .
thank you

Just do module.main() - there's nothing special about a function called main

Related

How can I execute all functions and individual functions as Run time arguments using python

I need to execute the class name with functions inside it and execute the functions inside the class individually on run time by passing arguments.
Python code saved as test.py
import sys
import threading
from threading import Thread
class test():
def func1(self):
print('hi im func1')
def func2(self):
print('hi im func2')
def func3(self):
print('hi im func3')
def runall(self):
if __name__ == '__main__':
Thread(target=self.func1).start()
Thread(target=self.func2).start()
Thread(target=self.func3).start()
if __name__ == '__main__':
try:
run = test()
run.runall()
globals()[sys.argv[1]]()
except KeyError:
raise KeyError('Invalid Function Name Passed in Argument! refer the code for valid Name.')
Trying to execute all functions inside class:
Runtime Execution: c:\ > python test.py test
Passed but gave error on
File "test.py", line 180, in
globals()sys.argv[2]
TypeError: 'test' object is not callable
Trying to execute only particular functions inside the class
Runtime Execution: c:\ > python test.py func1
Keyerror is getting thrown.
Can someone guide me on how to execute complete class and individual functions inside the class at runtime?
The first step works by me (on python 3.7.2)
> python3 test.py test
hi im func1
hi im func2
hi im func3
However this is triggered by the run.runall() statement. What version of Python do you run? don't you have another test variable in your work-space ?
For the second point, solution inspired by here, you could get the individual methods of the class running like this:
if __name__ == '__main__':
try:
run = test()
run.runall()
#globals()[sys.argv[1]]()
getattr(test(), sys.argv[1])()
except KeyError:
raise KeyError('Invalid Function Name Passed in Argument! refer the code for valid Name.')
result:
> python3 test.py func1
hi im func1
hi im func2
hi im func3
hi im func1
It worked for me Now I can Execute all Functions and separate functions individually. Thanks All For Your support and guide!!
if __name__ == '__main__':
try:
if sys.argv[2]=='test':
run = test()
run.runall()
else:
getattr(test(), sys.argv[2])()
except KeyError:
raise KeyError('Invalid Function Name Passed in Argument! refer the code for valid Name.')

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 ".

execute python script from another file (after reaching end of file)

I am trying to execute script (say, main.py) from another file (say, test.py), I don't want to call any function of main, instead i want to start executing the file from if __name__=="__main__":
Example:
test.py
def funA():
....
def funB():
....
#the last function of file
def funC():
#here i want to start executing main.py without calling any function.
main.py
def fun_x(arg1):
#do something
if __name__ == "__main__": #execution starts here
arg1=10
x(arg1)
Is it possible to call the main directly like this ?
You can just call the script "like a user would do" with The subprocess module.

main program while loop

I have a little Python program that uses keyboard input to run certain commands.
I setup everything in one main program loop but now I'm wondering, do I even need a main loop?
Here is what I mean:
mainProgramLoop = 1
while mainProgramLoop == 1:
print ("\nType in the command. ")
keyBoardInput= input("command:")
if keyBoardInput == "a":
#do this
elif keyBoardInput == "b":
#do this
Do I actually need that while loop?
Thanks!
No, you do not need a main loop if you use the cmd.Cmd class included with Python:
#! /usr/bin/env python3
import cmd
class App(cmd.Cmd):
prompt = 'Type in a command: '
def do_a(self, arg):
print('I am doing whatever action "a" is.')
def do_b(self, arg):
print('I am doing whatever action "b" is.')
if __name__ == '__main__':
App().cmdloop()
The documentation for the cmd module includes an example near the bottom to help get you started.

Multiprocessing beside a main loop

I'm struggling with a issue for some time now.
I'm building a little script which uses a main loop. This is a process that needs some attention from the users. The user responds on the steps and than some magic happens with use of some functions
Beside this I want to spawn another process which monitors the computer system for some specific events like pressing specif keys. If these events occur then it will launch the same functions as when the user gives in the right values.
So I need to make two processes:
-The main loop (which allows user interaction)
-The background "event scanner", which searches for specific events and then reacts on it.
I try this by launching a main loop and a daemon multiprocessing process. The problem is that when I launch the background process it starts, but after that I does not launch the main loop.
I simplified everything a little to make it more clear:
import multiprocessing, sys, time
def main_loop():
while 1:
input = input('What kind of food do you like?')
print(input)
def test():
while 1:
time.sleep(1)
print('this should run in the background')
if __name__ == '__main__':
try:
print('hello!')
mProcess = multiprocessing.Process(target=test())
mProcess.daemon = True
mProcess.start()
#after starting main loop does not start while it prints out the test loop fine.
main_loop()
except:
sys.exit(0)
You should do
mProcess = multiprocessing.Process(target=test)
instead of
mProcess = multiprocessing.Process(target=test())
Your code actually calls test in the parent process, and that call never returns.
You can use the locking synchronization to have a better control over your program's flow. Curiously, the input function raise an EOF error, but I'm sure you can find a workaround.
import multiprocessing, sys, time
def main_loop(l):
time.sleep(4)
l.acquire()
# raise an EOFError, I don't know why .
#_input = input('What kind of food do you like?')
print(" raw input at 4 sec ")
l.release()
return
def test(l):
i=0
while i<8:
time.sleep(1)
l.acquire()
print('this should run in the background : ', i+1, 'sec')
l.release()
i+=1
return
if __name__ == '__main__':
lock = multiprocessing.Lock()
#try:
print('hello!')
mProcess = multiprocessing.Process(target=test, args = (lock, ) ).start()
inputProcess = multiprocessing.Process(target=main_loop, args = (lock,)).start()
#except:
#sys.exit(0)

Categories

Resources