2

Say I have a (somewhat pointless) Python script

#!/usr/bin/python

a = 5

Is there a way to run this script from the interactive prompt such that after running if I type a I get

>>> a
5

and not

>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

More generally, if my script calculates something through a series of steps, is there a way to access that something after the script has finished (in the same kind of manner).

2
  • 1
    Does "run this script from the interactive prompt in a shell" mean "run this script from the interactive prompt", or "run this script in a shell and end up in the interactive prompt"? They're contradictory things, and the question seems ambiguous between them. For the first, it's from pointless import * (or, very rarely, execfile); for the second, it's python -i pointless.py. Commented Nov 20, 2012 at 20:10
  • I only included the word "shell" to define how I was starting the interactive prompt, so the correct interpretation is, "run this script from the [interactive prompt in a shell]" - i.e. the interactive prompt is running in a shell. I guess in hindsight this is both ambiguous and irrelevant, but I figured there are different ways to run the interactive prompt (e.g. from within other programs) which may change the answer. Commented Nov 20, 2012 at 20:48

1 Answer 1

7

Import it:

from yourscriptname import a

Each and every .py file in python is a module, and you can simply import it. If the file is called foo.py, import foo.

Sign up to request clarification or add additional context in comments.

1 Comment

What about if you're actually calculating something (i.e. it's not a hardcoded value) [oh snap, never mind]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.