Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does a python program tell if it's being run within emacs?

Tags:

python

emacs

I usually write python in emacs.

I'll often want to re-evaluate my file, which I can do with Ctrl-C Ctrl-C, which causes the interpreter to reload the entire file and then I can carry on playing.

so if I'm writing a program that takes input, I'll usually find myself with two lines:

lines = open("/home/jla/inputfile").readlines()
#lines = fileinput.input()

the first line is 'what to do while developing' (read from a known example input file) the second is 'what to do when run from the command line' (read from stdin, or a provided file name)

Obviously this is bad, so I am thinking:

if in_emacs():
     lines = open("/home/jla/inputfile").readlines()
if run_from_shell():
     lines = fileinput.input()
else:
     oops()

And I know how to write oops(), but I am a bit stuck with in_emacs() and run_from_shell(), and I wonder if you wise ones can help.

like image 929
John Lawrence Aspden Avatar asked Dec 16 '22 02:12

John Lawrence Aspden


2 Answers

Shells opened by emacs should have the environment variable EMACS=t. At least this works on my emacs, YMMV.

If that doesn't fly for you, here's how to find out what emacs-dependent environment variables python can see. Run from the shell and under emacs, and compare the outputs.

import os
for e in os.environ:
    if 'EMACS' in e:
        print e, os.environ[e]
like image 65
alexis Avatar answered Mar 28 '23 15:03

alexis


One option is to check for the presence of environment variables like EMACSPATH or EMACSLOADPATH. Also, depending on how you're starting Python inside Emacs, the value of the TERM environment variable may give you a useful clue.

like image 44
sanityinc Avatar answered Mar 28 '23 15:03

sanityinc