且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何确定Python脚本是否通过命令行运行?

更新时间:2023-12-04 21:37:04

我不认为有任何可靠的方法来检测这一点(特别是在跨平台的方式)。例如,在OS X上,当你双击一个 .py 文件,它用Python启动器调试,它运行在终端,等同于手动执行。

I don't think there's any reliable way to detect this (especially in a cross-platform manner). For example on OS X, when you double-click a .py file and it tuns with "Python Launcher", it runs in a terminal, identically to if you execute it manually.

虽然可能还有其他问题,但您可以使用 py2exe Platypus ,则可以让双击图标运行特定位的代码来区分( import mycode; mycode.main(gui = True)例如)

Although it may have other issues, you could package the script up with something like py2exe or Platypus, then you can have the double-clickable icon run a specific bit of code to differentiate (import mycode; mycode.main(gui = True) for example)