Script and command line access

I want to do the following:

I have a class that should provide several functions that need different inputs. And I would like to use these functions from other scripts or exclusively from the command line.

eg. I have a test class. It has a quicktest function (which basically just prints something). (From the command line) I want to be able to

$ python test.py quicktest "foo" "bar" 

While quicktest is the name of the function, the variables are "foo" and "bar".

Also (from inside another script) I want

 from test import test # this t = test() t.quicktest(["foo1", "bar1"]) # or this test().quicktest(["foo2", "bar2"]) 

I just can't get this to work. I managed to write a class for the first request, and the second for the second, but not for both. The problem is that I sometimes have to call functions through (self), sometimes not, and I also have to provide these parameters at any time, which is also quite difficult.

So, does anyone have any ideas?


This is what I already have:

It works only from the command line:

 class test: def quicktest(params): pprint(params) if (__name__ == '__main__'): if (sys.argv[1] == "quicktest"): quicktest(sys.argv) else: print "Wrong call." 

It works only from other scripts:

 class test: _params = sys.argv def quicktest(self, params): pprint(params) pprint(self._params) if (__name__ == '__main__'): if (sys.argv[1] == "quicktest"): quicktest() else: print "Wrong call" 
+4
source share
3 answers

try the following (note that unlike the if __name__ section, the part is not of the test class):

 class test: def quicktest(params): pprint(params) if __name__ == '__main__': if sys.argv[1] == "quicktest": testObj = test() testObj.quicktest(sys.argv) else: print "Wrong call." 

from other scripts:

 from test import test testObj = test() testObj.quicktest(...) 
+4
source

The if __name__ == '__main__': block if __name__ == '__main__': should be at the top level:

 class Test(object): # Python class names are capitalized and should inherit from object def __init__(self, *args): # parse args here so you can import and call with options too self.args = args def quicktest(self): return 'ret_value' if __name__ == '__main__': test = Test(sys.argv[1:]) 
+1
source

You can parse the command line using argparse to parse the value from the command line.

Your class that has a method and associates methods with arguments.

0
source

Source: https://habr.com/ru/post/1486774/


All Articles