68

I have a demo file: test.py. In the Windows Console I can run the file with: C:\>test.py

How can I execute the file in the Python Shell instead?

braaterAfrikaaner
  • 1,072
  • 10
  • 20
daniel__
  • 11,633
  • 15
  • 64
  • 91
  • 1
    What do you mean by "the python shell"? Did you run `python` from the command line? Or are you using IDLE or some other program which can also provide a Python `>>>` prompt? – S.Lott Sep 14 '11 at 18:17
  • Related posts - [How do I run a Python program?](https://stackoverflow.com/q/1522564/465053) & [How to make a Python script standalone executable to run without ANY dependency?](https://stackoverflow.com/q/5458048/465053) – RBT Aug 03 '18 at 06:17

6 Answers6

132

Use execfile for Python 2:

>>> execfile('C:\\test.py')

Use exec for Python 3

>>> exec(open("C:\\test.py").read())
Yusuf K.
  • 4,195
  • 1
  • 33
  • 69
phihag
  • 278,196
  • 72
  • 453
  • 469
  • 25
    in the version 3 (my version) the equivalent is: exec(open("C:\\test.py").read()). thanks! – daniel__ Sep 14 '11 at 18:22
  • 2
    @loops I'm getting: `SyntaxError: (Unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \uXXXX excape`. What does this mean? I tried changing the encoding of my .py document to Unicode but that didn't have any effect. – Musixauce3000 Apr 07 '16 at 17:57
  • @loops --Okay I just learned about `\U` unicode escapes. Apparetly you avoid his miscommunication by duplicating all backslashes followed by U's. But this produces an OSError 22 invalid argument `'c:\\users\username\\desktop\\test.py'` which is weird because I only duplicated the backslash in `\Users`. Why does the error show that I duplicated all the backslashes except for the one followed by username? – Musixauce3000 Apr 07 '16 at 18:07
  • @Musixauce3000 Please [post a new question](http://stackoverflow.com/questions/ask). – phihag Apr 07 '16 at 18:33
  • 1
    add an 'r' at the beginning if you get the SyntaxError: (Unicode error) 'unicodeescape' codec... Therefore it will be, exec(open(r"C:\\test.py").read()). – Subhashi Sep 20 '17 at 03:38
  • @phihag, the Python 3 version is verbose. Any expected problems defining `execfile = lambda file: exec(open(file).read())`? – alancalvitti Jan 03 '20 at 14:55
  • @alancalvitti No, that sounds sensible if for whatever reason you want to execute files frequently. – phihag Jan 03 '20 at 18:09
54

If you're wanting to run the script and end at a prompt (so you can inspect variables, etc), then use:

python -i test.py

That will run the script and then drop you into a Python interpreter.

Chris Phillips
  • 11,607
  • 3
  • 34
  • 45
20

It depends on what is in test.py. The following is an appropriate structure:

# suppose this is your 'test.py' file
def main():
 """This function runs the core of your program"""
 print("running main")

if __name__ == "__main__":
 # if you call this script from the command line (the shell) it will
 # run the 'main' function
 main()

If you keep this structure, you can run it like this in the command line (assume that $ is your command-line prompt):

$ python test.py
$ # it will print "running main"

If you want to run it from the Python shell, then you simply do the following:

>>> import test
>>> test.main() # this calls the main part of your program

There is no necessity to use the subprocess module if you are already using Python. Instead, try to structure your Python files in such a way that they can be run both from the command line and the Python interpreter.

Escualo
  • 40,844
  • 23
  • 87
  • 135
6

For newer version of python:

exec(open(filename).read())
Victor
  • 181
  • 2
  • 12
6

If you want to avoid writing all of this everytime, you can define a function :

def run(filename):
    exec(open(filename).read())

and then call it

run('filename.py')
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Hugo Trentesaux
  • 1,584
  • 1
  • 16
  • 30
  • This doesn't work for my use case since it doesn't import the variables. I'm not quite sure why not though. – wjandrea Feb 07 '21 at 22:03
2

From the same folder, you can do:

import test
Brendan Long
  • 53,280
  • 21
  • 146
  • 188