How does a python program tell if it runs in emacs?

I usually write python in emacs.

I often want to re-evaluate my file, which I can do with Ctrl-C Ctrl-C, which causes the interpreter to reload the whole file, and then I can continue to play.

therefore, if I write a program that accepts input, I usually find myself with two lines:

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

the first line is "what to do during development" (read from the input file with a well-known example) the second is "what to do if you run from the command line" (read from stdin or the file name provided)

Obviously this is bad, so I think:

 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'm a little stuck with in_emacs() and run_from_shell() , and I wonder if you can help.

+4
source share
2 answers

In shells opened by emacs, there must be an environment variable EMACS=t . At least it works on my emacs, YMMV.

If this is not for you, here's how to find out which emacs-dependent environment variables python can see. Run from shell and under emacs and compare outputs.

 import os for e in os.environ: if 'EMACS' in e: print e, os.environ[e] 
+10
source

One option is to check for environment variables such as EMACSPATH or EMACSLOADPATH . Also, depending on how you run Python inside Emacs, the value of the TERM environment variable may give you a helpful hint.

+2
source

Source: https://habr.com/ru/post/1403203/


All Articles