First time here? Check out the FAQ!

Ask Your Question
1

How can I distinguish between Sage and Python?

asked 0 years ago

anonymous user

Anonymous

Is there a constant defined in SageMath that I can use to distinguish whether Sage is running or pure Python? Something that I can use like this:

SAGE = False
try:
    SAGE = ZZ
except NameError:
    pass
print(SAGE)

Contrary to my expectations, the Sage Cell Server outputs 'Integer Ring' in both cases.

Preview: (hide)

3 Answers

Sort by » oldest newest most voted
3

answered 0 years ago

It depends on what you mean by "Sage is running". If you mean, "have the standard Sage commands, etc., been imported and are ready for use," then you could test

import sys
if 'sage' in sys.modules:
    print('The Sage library has been imported')

This seems to be the case with the Sage Cell server for both Sage and Python: Sage has been imported in both cases. That's why your test isn't distinguishing the two. Along the same lines, print(sage.version.version) returns 10.2 in both Sage and Python on the Sage Cell server.

If you mean, "is Sage's preparser running," then the answer from @PedroBrazil is correct. In Python, ^ means bitwise exclusive or, while by default in Sage, ^ is exponentiation. The preparser can be turned off while still running Sage, though, so this is not a perfect test.

My guess is that the "Python" setting for the Sage Cell Server imports all of Sage and just turns off the preparser. So again, it depends on what you need to test, why you need to know whether it's Sage or Python.

Preview: (hide)
link
2

answered 0 years ago

PedroBrazil gravatar image

This 1-liner fulfills the purpose (tested with the Sage Cell Server).

def is_sage_running(): return 2^3 != 1
print(is_sage_running())
Preview: (hide)
link
0

answered 0 years ago

Peter Luschny gravatar image

Sage Math Server's behavior is clearly misleading the user and should be changed immediately.

def issage():
    try:
        import sage.all
        return True
    except ImportError:
        return False
print(issage())

This should work independent of the preparser.

Preview: (hide)
link

Comments

1

This tests whether Sage can be imported, not whether it already has been, and furthermore it imports it if it can be: it has side effects.

John Palmieri gravatar imageJohn Palmieri ( 0 years ago )

That's right. Then it's not really any good.

Peter Luschny gravatar imagePeter Luschny ( 0 years ago )

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 0 years ago

Seen: 168 times

Last updated: Jan 29