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.
Related
I have a flask python file that i want to open when i start the main python file.
main python file
start flask python file
continue with it's own independent processes (threading)
Which solution to take since i do not want the execution of the flask app to hinder the performance of the later processes. Not sure if i should do a subprocess or exec file?
both files are pretty independent of each other.
if I understood correctly, you can create a daemon thread for flask and continue with the execution of main program.
If you have a independent_module.py like this:
# independent_module.py
# your independent functions
def start():
pass
Then your main file would look something like this:
# main.py file
import threading
from flask import Flask
import main
app = Flask(__name__)
#app.route("/health")
def health():
return "OK"
#app.route("/ping")
def ping():
return "Et. Voila!!"
def run_server_api():
app.run(host='0.0.0.0', port=8080)
def main():
flask_thread = threading.Thread(target=run_server_api, daemon=True)
flask_thread.start()
# continue with your main program functions
independent_module.start()
if __name__ == "__main__":
# execute main
main()
You can simply execute python main.py
i'm trying to code in multithreading,one of my thread supposed to create a file ,and other thread should use the file. the thread sync well.
the problem is that the file object writing into the disk when the code finish or when i'm press the terminate button (i'm using PyCharm pro).
little example:
1. i tried to use service that call other script test1 , but it doesn't work well.
i supposed that if test1 will create the file , he can do that many times as long as service didn't finish the running .
i tried to create a file and then to use while true- to imagine that the code is keep running
my question is how can i force my code to create the file before my main code finish?
service.py
import time
import runpy
import test1
def anotherChance(global_vars=None, local_vars=None):
with open("test1.py") as f:
code = compile(f.read(), "test1.py", 'exec')
exec(code, global_vars, local_vars)
def service_func():
print('service func')
print('while loop')
while True:
print(1234)
time.sleep(5)
test1.some_func()
if __name__ == '__main__':
#exec(open("test1.py").read()) ##1 another wrong sol
#anotherChance() ##2 another wrong sol
#service_func()
test1.some_func()
service_func()
test1.py
import os
def tempreding ():
with open('betext_file.json', 'w') as file:
file.write('helloo')
print(file.fileno())
def some_func():
print('in test 1, unproductive')
#infile=open('abcs.json','w')
#infile.write('aabbcc')
tempreding()
if __name__ == '__main__':
#print("I am a test")
#print(" I do nothing .")
some_func()
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 ".
I have 2 files a.py and b.py as follows:
a.py
import b.py
Test="abc"
def main(args):
global Test
if args.target=="this":
Test="klm"
b.fun()
#rest of the body which I intend to execute only once
#hence I cannot call main() again
if __name__ == "__main__":
#some arguments are parsed
args = parser.parse_args()
main(args)
b.py
import a
print a.Test
EDIT: Output:
python a.py
abc
So basically my question is why is the Test variable not getting updated in b.py and how can I make this work? Thanks.
import a
a.main()
print a.Test
a.Test = "new Value"
print a.Text
You never invoke the main function. When you import a module, __name__ is not "__main__", so your main() never runs. When you run a.py directly it will run main()
Added due to question edit:
You need to consider the ordering of the imports execution. Consider these working files.
a.py
print("Entering a")
import argparse
import b
Test="abc"
print("Id of Test: ", id(Test))
def main(args):
global Test
if args.target=="this":
Test="klm"
b.fun()
#rest of the body which I intend to execute only once
#hence I cannot call main() again
if __name__ == "__main__":
#some arguments are parsed
print('Entering main')
parser = argparse.ArgumentParser()
parser.add_argument('--target', dest='target', type=str)
args = parser.parse_args()
main(args)
b.py
print("Entering b")
import a
print a.Test
def fun():
pass
The console produces the following:
$ python a.py
Entering a
Entering b
Entering a
('Id of Test: ', 40012016L)
abc
('Id of Test: ', 40012016L)
Entering main
The problem is, when you import a python module/file, you will immediately execute all the statements in that module. As such, you have a problem with your dependencies (aka imports), because b is importing a before the value of Test is 'corrected' and then immediately acting on this.
Consider two changes. First, introduce a third file config.py that contains this configuration information and that b does not import a. Second, move all your statements that require this config in b into functions that are called/bootstrapped by a, as obviously intended.
Previous answer:
I have a solution demonstrating the issue, by only modifying b.py
def fun(): # Added because your main calls this. An error?
pass
from a import Test, main
import a
print Test # prints 'abc'
print a.Test # prints 'abc'
main()
print Test # prints 'abc'
print a.Test # prints 'klm'
Within the python interpretor, I can produce the following:
>>> import b
abc
abc
abc
klm
In your code, you create a new variable called Test with the command from a import Test that points to the original string object. You actually want to access the Test variable owned by the module a.
In a.py you run main in the if statement:
if __name__ == "__main__":
main()
Only executes main() if that is the main script. When you import the module all the code in the if block is not run because it is not the main script. To have the main method be called remove the if statement or just call main in b.py.
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