如何使用python在终端/命令提示符下运行方法

2024-04-20 01:44:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我这里有文件1:

#File1

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

  def efg(self)
   ---

这是文件2:

#File2
from File1 import MyClass1

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

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

if __name__== "__main__":
  test()

问题: 如何仅在终端/命令提示符下调用test2方法?你知道吗

注:
1我正在使用python3
2我是否需要在file2中添加另一个“class(例如MyClass2)”,以便专门调用test2
三。请举一些例子供参考。你知道吗


Tags: 文件fromimportselfdeffile1classfile2
1条回答
网友
1楼 · 发布于 2024-04-20 01:44:55

如果file2实际上被称为file2.py,并且在你的PYTHONPATH中,你可以说

python3 -c 'import file2; test2()'

如果没有,也许可以试试

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

第三种可能的解决办法是使最后一条更加复杂。你知道吗

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

就这样说吧

python3 file2 test2

采取elif分支。你知道吗

相关问题 更多 >