如何确定Python脚本是否通过命令行运行? [英] How to determine if Python script was run via command line?
问题描述
我希望我的Python脚本在退出之前暂停,类似于:
I would like my Python script to pause before exiting using something similar to:
code> raw_input(按Enter键关闭。)
raw_input("Press enter to close.")
,但仅当未通过命令行运行。命令行程序不应该这样。
but only if it is NOT run via command line. Command line programs shouldn't behave this way.
有一种方法可以确定我的Python脚本从命令行调用:
Is there a way to determine if my Python script was invoked from the command line:
$ python myscript.py
是否双击 myscript.py
使用操作系统中的默认解释器打开它?
verses double-clicking myscript.py
to open it with the default interpreter in the OS?
推荐答案
我不认为有任何可靠的方法来检测这一点(特别是在跨平台的方式)。例如,在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)
这篇关于如何确定Python脚本是否通过命令行运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!