确定是否从Python中的脚本调用程序 [英] Determine if the program is called from a script in Python

查看:64
本文介绍了确定是否从Python中的脚本调用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

doa

#!/bin/sh
myexe

myexe

if sys.stdout.isatty():
    print 'from a script'
else:
    print 'not from a script'

输出(如果我从终端执行doa):

OUTPUT (if i execute doa from terminal):

not from a script

输出(如果我从终端执行myexe):

OUTPUT (if i execute myexe from terminal):

not from a script

如果要从doa执行,我希望它说'from a script'

I want it to say 'from a script' if executed from doa

问题:myexe是否有可能知道它是从bash脚本执行的?

Question: is it possible for myexe to know that it's being executed from a bash script?

推荐答案

您可以使用psutil询问ID为父进程ID的进程的名称:

You can use psutil to ask for the name of the process with id the parent process id:

import psutil
import os

ppid = os.getppid() # Get parent process id
psutil.Process(ppid).name() == "bash"

您可以使用pip命令安装psutil:

pip install psutil

这篇关于确定是否从Python中的脚本调用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆