python如何看执行过程,如何确定Python脚本是否通过命令行运行?

在Python中,没有可靠的方法直接检测脚本是通过命令行还是图形化方式启动的。通常,当双击.py文件运行时,它可能会在默认的OS解释器中打开,行为与手动从终端执行相似。尽管存在一些潜在问题,但可以考虑使用如py2exe或Platypus这样的打包工具,以使双击运行的脚本能执行特定代码来区分执行方式。
摘要由CSDN通过智能技术生成

Background

I would like my Python script to pause before exiting using something similar to:

raw_input("Press enter to close.")

but only if it is NOT run via command line. Command line programs shouldn't behave this way.

Question

Is there a way to determine if my Python script was invoked from the command line:

$ python myscript.py

verses double-clicking myscript.py to open it with the default interpreter in the OS?

解决方案

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.

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值