Determine if the program is called from a script in Python

橙三吉。 提交于 2019-12-25 18:54:26

问题


doa

#!/bin/sh
myexe

myexe

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

OUTPUT (if i execute doa from terminal):

not from a script

OUTPUT (if i execute myexe from terminal):

not from a script

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

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


回答1:


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"

You can install psutil with pip command:

pip install psutil


来源:https://stackoverflow.com/questions/29239698/determine-if-the-program-is-called-from-a-script-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!