Dipesh
Dipesh

Reputation: 17

Running a Python script from the Python Shell

I wrote a script and saved it as test.py (code shown below). And when I run it from the script (Run Module 5), I get the result in the Python Shell.

But I have tried multiple suggestions available online to have it run from the Python Shell instead to which I fail (one error pasted below).

How can I run a python script from the python shell? The version of Python I am running is 3.7.3 and in Windows.

#!/usr/bin/python3

print(" Hello, world!")

exec(open(test.py).read())

Output:

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    exec(open(test.py).read())
NameError: name 'test' is not defined

Upvotes: 1

Views: 842

Answers (2)

whackamadoodle3000
whackamadoodle3000

Reputation: 6748

You don't need the last line for it to run. All you need is:

!/usr/bin/python3

print(" Hello, world!")

If you want to run it from another file, don't use exec. Instead, import it.

import test

Upvotes: 2

paul
paul

Reputation: 468

You need to pass the "test.py" as a string (use quotes). test is not a known object.

Upvotes: 1

Related Questions