How to use a module with arguments?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







-2















I have a module, called T, has a couple of functions and the main part, where calls these functions. From another module, I want to use this module. The main scheme is like:



"""Module T"""
def parse_args():
parser = argparse.ArgumentParser(description='Desc')
parser.add_argument('something')

def foo():
pass

if __name__ == "__main__":
args = parse_args()
foo()


And the other module I want to use:



"""Module M"""
def foo():
pass

def do_something():
"""Where I want to use module T's main"""


I have used module T from terminal with arguments and worked fine. The question may be easy but, how can I use it's main with parameters?










share|improve this question























  • If you really need to call its main, I think the only way to do it is calling it as an external program. But why would you want to call its main in the first place? Why not simply calling Ts methods inside directly?

    – Tobias Brösamle
    Nov 16 '18 at 13:58













  • Seems like the easiest solution might just be to pull those two lines into a main() function inside T, then call main() both from T and from M.

    – 0x5453
    Nov 16 '18 at 13:58











  • @TobiasBrösamle I'm new to python and it's logic about main. I have searched an answer to this but didn't find any. I thought a solution as the same as 0x5453's but insisted to find an easier way. You both of you might be right.

    – emremrah
    Nov 16 '18 at 14:02


















-2















I have a module, called T, has a couple of functions and the main part, where calls these functions. From another module, I want to use this module. The main scheme is like:



"""Module T"""
def parse_args():
parser = argparse.ArgumentParser(description='Desc')
parser.add_argument('something')

def foo():
pass

if __name__ == "__main__":
args = parse_args()
foo()


And the other module I want to use:



"""Module M"""
def foo():
pass

def do_something():
"""Where I want to use module T's main"""


I have used module T from terminal with arguments and worked fine. The question may be easy but, how can I use it's main with parameters?










share|improve this question























  • If you really need to call its main, I think the only way to do it is calling it as an external program. But why would you want to call its main in the first place? Why not simply calling Ts methods inside directly?

    – Tobias Brösamle
    Nov 16 '18 at 13:58













  • Seems like the easiest solution might just be to pull those two lines into a main() function inside T, then call main() both from T and from M.

    – 0x5453
    Nov 16 '18 at 13:58











  • @TobiasBrösamle I'm new to python and it's logic about main. I have searched an answer to this but didn't find any. I thought a solution as the same as 0x5453's but insisted to find an easier way. You both of you might be right.

    – emremrah
    Nov 16 '18 at 14:02














-2












-2








-2








I have a module, called T, has a couple of functions and the main part, where calls these functions. From another module, I want to use this module. The main scheme is like:



"""Module T"""
def parse_args():
parser = argparse.ArgumentParser(description='Desc')
parser.add_argument('something')

def foo():
pass

if __name__ == "__main__":
args = parse_args()
foo()


And the other module I want to use:



"""Module M"""
def foo():
pass

def do_something():
"""Where I want to use module T's main"""


I have used module T from terminal with arguments and worked fine. The question may be easy but, how can I use it's main with parameters?










share|improve this question














I have a module, called T, has a couple of functions and the main part, where calls these functions. From another module, I want to use this module. The main scheme is like:



"""Module T"""
def parse_args():
parser = argparse.ArgumentParser(description='Desc')
parser.add_argument('something')

def foo():
pass

if __name__ == "__main__":
args = parse_args()
foo()


And the other module I want to use:



"""Module M"""
def foo():
pass

def do_something():
"""Where I want to use module T's main"""


I have used module T from terminal with arguments and worked fine. The question may be easy but, how can I use it's main with parameters?







python






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 16 '18 at 13:54









emremrahemremrah

809




809













  • If you really need to call its main, I think the only way to do it is calling it as an external program. But why would you want to call its main in the first place? Why not simply calling Ts methods inside directly?

    – Tobias Brösamle
    Nov 16 '18 at 13:58













  • Seems like the easiest solution might just be to pull those two lines into a main() function inside T, then call main() both from T and from M.

    – 0x5453
    Nov 16 '18 at 13:58











  • @TobiasBrösamle I'm new to python and it's logic about main. I have searched an answer to this but didn't find any. I thought a solution as the same as 0x5453's but insisted to find an easier way. You both of you might be right.

    – emremrah
    Nov 16 '18 at 14:02



















  • If you really need to call its main, I think the only way to do it is calling it as an external program. But why would you want to call its main in the first place? Why not simply calling Ts methods inside directly?

    – Tobias Brösamle
    Nov 16 '18 at 13:58













  • Seems like the easiest solution might just be to pull those two lines into a main() function inside T, then call main() both from T and from M.

    – 0x5453
    Nov 16 '18 at 13:58











  • @TobiasBrösamle I'm new to python and it's logic about main. I have searched an answer to this but didn't find any. I thought a solution as the same as 0x5453's but insisted to find an easier way. You both of you might be right.

    – emremrah
    Nov 16 '18 at 14:02

















If you really need to call its main, I think the only way to do it is calling it as an external program. But why would you want to call its main in the first place? Why not simply calling Ts methods inside directly?

– Tobias Brösamle
Nov 16 '18 at 13:58







If you really need to call its main, I think the only way to do it is calling it as an external program. But why would you want to call its main in the first place? Why not simply calling Ts methods inside directly?

– Tobias Brösamle
Nov 16 '18 at 13:58















Seems like the easiest solution might just be to pull those two lines into a main() function inside T, then call main() both from T and from M.

– 0x5453
Nov 16 '18 at 13:58





Seems like the easiest solution might just be to pull those two lines into a main() function inside T, then call main() both from T and from M.

– 0x5453
Nov 16 '18 at 13:58













@TobiasBrösamle I'm new to python and it's logic about main. I have searched an answer to this but didn't find any. I thought a solution as the same as 0x5453's but insisted to find an easier way. You both of you might be right.

– emremrah
Nov 16 '18 at 14:02





@TobiasBrösamle I'm new to python and it's logic about main. I have searched an answer to this but didn't find any. I thought a solution as the same as 0x5453's but insisted to find an easier way. You both of you might be right.

– emremrah
Nov 16 '18 at 14:02












2 Answers
2






active

oldest

votes


















2














Add a run function (or main or whatever you like) to your module that accepts your command line, and make sure that parse_args optionally accepts an arbitrary list as well:



def parse_args(args=None):
parser = argparse.ArgumentParser(description='Desc')
parser.add_argument('something')
return parser.parse_args(args)

def foo():
pass

def run(args=None):
args = parse_args(args)
foo()

if __name__ == "__main__":
run()


Basically, instead of trying to simulate the import operation and injecting sys.argv (which might actually be possible), you can just factor out the part that the import runs that's of interest to you, and provide access to it:



import T

T.run() # Uses sys.argv
T.run(['my', 'list', '--of', 'args'])


While totally untested, you can possibly also do something like the following (please don't though, this is just for fun):



import sys
from importlib import reload

sys.argv[1:] = my_args

if 'T' in sys.modules:
reload(sys.modules['T'])
else:
import T


But then you'd need to remove the import guard in T.py. Unless you wanted to implement your own module loading sequence, which would let you inject T.__name__, rather than having to modify the import guard: Injecting variables into an import namespace






share|improve this answer


























  • I think you'll want to call run, not foo, from the guarded block.

    – chepner
    Nov 16 '18 at 14:00











  • @chepner. Yes. Fixed. Typing fast on mobile :)

    – Mad Physicist
    Nov 16 '18 at 14:01











  • So I just need to import T in M, then do T.run()? If so, why I need the main part?

    – emremrah
    Nov 16 '18 at 14:05











  • I also think you wanted to give args to parse_args inside your run method.

    – Tobias Brösamle
    Nov 16 '18 at 14:05











  • I think this is the solution then. I will inform you. Thanks a lot. Easier than I thought :)

    – emremrah
    Nov 16 '18 at 14:07



















2














The if __name__ ... pattern is executed if the script is called directly, so the real solution is to call foo in your entrypoint. The if __name__ ... patter basically protects lines of code from being executed on import. For example, this is a very convenient pattern for testing - just put your tests in the protected block. The straightforward way to do what you're asking:



"""Module M"""
def bar():
pass

def do_something(args):
args = parse_args()
module_t.foo()


If you want module M to be completely "fire and forget" then Mad Physicist's answer is for you.






share|improve this answer


























  • What is module_m?

    – Mad Physicist
    Nov 16 '18 at 14:05











  • Good catch should have been module_t @MadPhysicist!

    – Charles Landau
    Nov 16 '18 at 14:06












Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53339242%2fhow-to-use-a-module-with-arguments%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














Add a run function (or main or whatever you like) to your module that accepts your command line, and make sure that parse_args optionally accepts an arbitrary list as well:



def parse_args(args=None):
parser = argparse.ArgumentParser(description='Desc')
parser.add_argument('something')
return parser.parse_args(args)

def foo():
pass

def run(args=None):
args = parse_args(args)
foo()

if __name__ == "__main__":
run()


Basically, instead of trying to simulate the import operation and injecting sys.argv (which might actually be possible), you can just factor out the part that the import runs that's of interest to you, and provide access to it:



import T

T.run() # Uses sys.argv
T.run(['my', 'list', '--of', 'args'])


While totally untested, you can possibly also do something like the following (please don't though, this is just for fun):



import sys
from importlib import reload

sys.argv[1:] = my_args

if 'T' in sys.modules:
reload(sys.modules['T'])
else:
import T


But then you'd need to remove the import guard in T.py. Unless you wanted to implement your own module loading sequence, which would let you inject T.__name__, rather than having to modify the import guard: Injecting variables into an import namespace






share|improve this answer


























  • I think you'll want to call run, not foo, from the guarded block.

    – chepner
    Nov 16 '18 at 14:00











  • @chepner. Yes. Fixed. Typing fast on mobile :)

    – Mad Physicist
    Nov 16 '18 at 14:01











  • So I just need to import T in M, then do T.run()? If so, why I need the main part?

    – emremrah
    Nov 16 '18 at 14:05











  • I also think you wanted to give args to parse_args inside your run method.

    – Tobias Brösamle
    Nov 16 '18 at 14:05











  • I think this is the solution then. I will inform you. Thanks a lot. Easier than I thought :)

    – emremrah
    Nov 16 '18 at 14:07
















2














Add a run function (or main or whatever you like) to your module that accepts your command line, and make sure that parse_args optionally accepts an arbitrary list as well:



def parse_args(args=None):
parser = argparse.ArgumentParser(description='Desc')
parser.add_argument('something')
return parser.parse_args(args)

def foo():
pass

def run(args=None):
args = parse_args(args)
foo()

if __name__ == "__main__":
run()


Basically, instead of trying to simulate the import operation and injecting sys.argv (which might actually be possible), you can just factor out the part that the import runs that's of interest to you, and provide access to it:



import T

T.run() # Uses sys.argv
T.run(['my', 'list', '--of', 'args'])


While totally untested, you can possibly also do something like the following (please don't though, this is just for fun):



import sys
from importlib import reload

sys.argv[1:] = my_args

if 'T' in sys.modules:
reload(sys.modules['T'])
else:
import T


But then you'd need to remove the import guard in T.py. Unless you wanted to implement your own module loading sequence, which would let you inject T.__name__, rather than having to modify the import guard: Injecting variables into an import namespace






share|improve this answer


























  • I think you'll want to call run, not foo, from the guarded block.

    – chepner
    Nov 16 '18 at 14:00











  • @chepner. Yes. Fixed. Typing fast on mobile :)

    – Mad Physicist
    Nov 16 '18 at 14:01











  • So I just need to import T in M, then do T.run()? If so, why I need the main part?

    – emremrah
    Nov 16 '18 at 14:05











  • I also think you wanted to give args to parse_args inside your run method.

    – Tobias Brösamle
    Nov 16 '18 at 14:05











  • I think this is the solution then. I will inform you. Thanks a lot. Easier than I thought :)

    – emremrah
    Nov 16 '18 at 14:07














2












2








2







Add a run function (or main or whatever you like) to your module that accepts your command line, and make sure that parse_args optionally accepts an arbitrary list as well:



def parse_args(args=None):
parser = argparse.ArgumentParser(description='Desc')
parser.add_argument('something')
return parser.parse_args(args)

def foo():
pass

def run(args=None):
args = parse_args(args)
foo()

if __name__ == "__main__":
run()


Basically, instead of trying to simulate the import operation and injecting sys.argv (which might actually be possible), you can just factor out the part that the import runs that's of interest to you, and provide access to it:



import T

T.run() # Uses sys.argv
T.run(['my', 'list', '--of', 'args'])


While totally untested, you can possibly also do something like the following (please don't though, this is just for fun):



import sys
from importlib import reload

sys.argv[1:] = my_args

if 'T' in sys.modules:
reload(sys.modules['T'])
else:
import T


But then you'd need to remove the import guard in T.py. Unless you wanted to implement your own module loading sequence, which would let you inject T.__name__, rather than having to modify the import guard: Injecting variables into an import namespace






share|improve this answer















Add a run function (or main or whatever you like) to your module that accepts your command line, and make sure that parse_args optionally accepts an arbitrary list as well:



def parse_args(args=None):
parser = argparse.ArgumentParser(description='Desc')
parser.add_argument('something')
return parser.parse_args(args)

def foo():
pass

def run(args=None):
args = parse_args(args)
foo()

if __name__ == "__main__":
run()


Basically, instead of trying to simulate the import operation and injecting sys.argv (which might actually be possible), you can just factor out the part that the import runs that's of interest to you, and provide access to it:



import T

T.run() # Uses sys.argv
T.run(['my', 'list', '--of', 'args'])


While totally untested, you can possibly also do something like the following (please don't though, this is just for fun):



import sys
from importlib import reload

sys.argv[1:] = my_args

if 'T' in sys.modules:
reload(sys.modules['T'])
else:
import T


But then you'd need to remove the import guard in T.py. Unless you wanted to implement your own module loading sequence, which would let you inject T.__name__, rather than having to modify the import guard: Injecting variables into an import namespace







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 16 '18 at 14:38

























answered Nov 16 '18 at 14:00









Mad PhysicistMad Physicist

38.7k1679112




38.7k1679112













  • I think you'll want to call run, not foo, from the guarded block.

    – chepner
    Nov 16 '18 at 14:00











  • @chepner. Yes. Fixed. Typing fast on mobile :)

    – Mad Physicist
    Nov 16 '18 at 14:01











  • So I just need to import T in M, then do T.run()? If so, why I need the main part?

    – emremrah
    Nov 16 '18 at 14:05











  • I also think you wanted to give args to parse_args inside your run method.

    – Tobias Brösamle
    Nov 16 '18 at 14:05











  • I think this is the solution then. I will inform you. Thanks a lot. Easier than I thought :)

    – emremrah
    Nov 16 '18 at 14:07



















  • I think you'll want to call run, not foo, from the guarded block.

    – chepner
    Nov 16 '18 at 14:00











  • @chepner. Yes. Fixed. Typing fast on mobile :)

    – Mad Physicist
    Nov 16 '18 at 14:01











  • So I just need to import T in M, then do T.run()? If so, why I need the main part?

    – emremrah
    Nov 16 '18 at 14:05











  • I also think you wanted to give args to parse_args inside your run method.

    – Tobias Brösamle
    Nov 16 '18 at 14:05











  • I think this is the solution then. I will inform you. Thanks a lot. Easier than I thought :)

    – emremrah
    Nov 16 '18 at 14:07

















I think you'll want to call run, not foo, from the guarded block.

– chepner
Nov 16 '18 at 14:00





I think you'll want to call run, not foo, from the guarded block.

– chepner
Nov 16 '18 at 14:00













@chepner. Yes. Fixed. Typing fast on mobile :)

– Mad Physicist
Nov 16 '18 at 14:01





@chepner. Yes. Fixed. Typing fast on mobile :)

– Mad Physicist
Nov 16 '18 at 14:01













So I just need to import T in M, then do T.run()? If so, why I need the main part?

– emremrah
Nov 16 '18 at 14:05





So I just need to import T in M, then do T.run()? If so, why I need the main part?

– emremrah
Nov 16 '18 at 14:05













I also think you wanted to give args to parse_args inside your run method.

– Tobias Brösamle
Nov 16 '18 at 14:05





I also think you wanted to give args to parse_args inside your run method.

– Tobias Brösamle
Nov 16 '18 at 14:05













I think this is the solution then. I will inform you. Thanks a lot. Easier than I thought :)

– emremrah
Nov 16 '18 at 14:07





I think this is the solution then. I will inform you. Thanks a lot. Easier than I thought :)

– emremrah
Nov 16 '18 at 14:07













2














The if __name__ ... pattern is executed if the script is called directly, so the real solution is to call foo in your entrypoint. The if __name__ ... patter basically protects lines of code from being executed on import. For example, this is a very convenient pattern for testing - just put your tests in the protected block. The straightforward way to do what you're asking:



"""Module M"""
def bar():
pass

def do_something(args):
args = parse_args()
module_t.foo()


If you want module M to be completely "fire and forget" then Mad Physicist's answer is for you.






share|improve this answer


























  • What is module_m?

    – Mad Physicist
    Nov 16 '18 at 14:05











  • Good catch should have been module_t @MadPhysicist!

    – Charles Landau
    Nov 16 '18 at 14:06
















2














The if __name__ ... pattern is executed if the script is called directly, so the real solution is to call foo in your entrypoint. The if __name__ ... patter basically protects lines of code from being executed on import. For example, this is a very convenient pattern for testing - just put your tests in the protected block. The straightforward way to do what you're asking:



"""Module M"""
def bar():
pass

def do_something(args):
args = parse_args()
module_t.foo()


If you want module M to be completely "fire and forget" then Mad Physicist's answer is for you.






share|improve this answer


























  • What is module_m?

    – Mad Physicist
    Nov 16 '18 at 14:05











  • Good catch should have been module_t @MadPhysicist!

    – Charles Landau
    Nov 16 '18 at 14:06














2












2








2







The if __name__ ... pattern is executed if the script is called directly, so the real solution is to call foo in your entrypoint. The if __name__ ... patter basically protects lines of code from being executed on import. For example, this is a very convenient pattern for testing - just put your tests in the protected block. The straightforward way to do what you're asking:



"""Module M"""
def bar():
pass

def do_something(args):
args = parse_args()
module_t.foo()


If you want module M to be completely "fire and forget" then Mad Physicist's answer is for you.






share|improve this answer















The if __name__ ... pattern is executed if the script is called directly, so the real solution is to call foo in your entrypoint. The if __name__ ... patter basically protects lines of code from being executed on import. For example, this is a very convenient pattern for testing - just put your tests in the protected block. The straightforward way to do what you're asking:



"""Module M"""
def bar():
pass

def do_something(args):
args = parse_args()
module_t.foo()


If you want module M to be completely "fire and forget" then Mad Physicist's answer is for you.







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 16 '18 at 14:06

























answered Nov 16 '18 at 14:01









Charles LandauCharles Landau

2,8011317




2,8011317













  • What is module_m?

    – Mad Physicist
    Nov 16 '18 at 14:05











  • Good catch should have been module_t @MadPhysicist!

    – Charles Landau
    Nov 16 '18 at 14:06



















  • What is module_m?

    – Mad Physicist
    Nov 16 '18 at 14:05











  • Good catch should have been module_t @MadPhysicist!

    – Charles Landau
    Nov 16 '18 at 14:06

















What is module_m?

– Mad Physicist
Nov 16 '18 at 14:05





What is module_m?

– Mad Physicist
Nov 16 '18 at 14:05













Good catch should have been module_t @MadPhysicist!

– Charles Landau
Nov 16 '18 at 14:06





Good catch should have been module_t @MadPhysicist!

– Charles Landau
Nov 16 '18 at 14:06


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53339242%2fhow-to-use-a-module-with-arguments%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Xamarin.iOS Cant Deploy on Iphone

Glorious Revolution

Dulmage-Mendelsohn matrix decomposition in Python