0

I have the file1 here:

#File1

class MyClass1():
  def abc(self)
   ---

  def efg(self)
   ---

and here's the file2:

#File2
from File1 import MyClass1

def test1()
  callfromfile1 = Myclass1()
  callfromfile1.abc()

def test2()
  callfromfile1 = Myclass1()
  callfromfile1.efg()

if __name__== "__main__":
  test()

Prob: How to call test2 method only in terminal/command prompt?

note:
1. I'm using python3
2. Should I need to add another "class (eg. MyClass2)" above in file2 in order to call the test2 specicifically?
3. Please give some example for reference.

8
  • Apart from the import from selenium import webdriver is there anything related to selenium? Am I missing something? Commented Jun 17, 2018 at 17:54
  • 1
    Sorry, I didn't know what syntax is specifically for python and selenium since i'm using this for selenium testing. thnx Commented Jun 17, 2018 at 17:59
  • It is a pure Pythonic concept and have no relation with Selenium. Update the question dropping the line from selenium import webdriver and selenium tag to clear up the confusion Commented Jun 17, 2018 at 18:02
  • 1
    done! thnx for noticing it. Commented Jun 17, 2018 at 18:09
  • Are you willing to pass additional command line arguments to the script? Commented Jun 17, 2018 at 18:12

1 Answer 1

1

If file2 is actually called file2.py and is in your PYTHONPATH you can say

python3 -c 'import file2; test2()'

If not, maybe try

(cat file2; echo 'test2()') | python3

A third possible solution is to make the last clause more complex.

if __name__ == '__main__':
    import sys
    if len(sys.argv) == 1:
        test()
    elif 'test2' in sys.argv[1:]:
        test2()
    # maybe more cases here in the future

and call it like

python3 file2 test2

to take the elif branch.

Sign up to request clarification or add additional context in comments.

2 Comments

As an aside, a library called click makes it very easy to expose individual functions inside a Python source file to a calling shell.
Yes, it is the actual file named file1.py and file2.py

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.