Import a script in IDLE
Asked Answered
D

3

10

This has probably been asked before, and is really basic, but:

I'm using Windows 7. I have Idle for Python 2.4.4 and 3.1. I have some scripts residing in arbitrary locations on my file system. I'd like to import them and play around with their types. How can I do so?

In Ubuntu, on the command line, import scriptname works if the directory I called python from contains scriptname. How would I import a script from somewhere else?

Dismiss answered 3/3, 2011 at 2:19 Comment(1)
V
8

In idle you could append a path containing your scriptname.py file.

>>> import pprint
>>> import sys
>>> print pprint.pprint(sys.path)
# you could just move your scriptname.py to a directory in the sys.path list
>>> sys.path.append(r"C:\Users\You\")
>>> import scriptname

You could also customize the PYTHONPATH environment variable in windows to include other directories like "C:\Users\You\lib"

Vachil answered 3/3, 2011 at 2:59 Comment(2)
Don't forget escape the backslashes in the directory you add to sys.path (sys.path.append("C:\\Users\\You\\") or simply sys.path.append(r"C:\Users\You\"))Convulsion
...or sys.path.append('C:/Users/You')Mayfly
J
4

To import a script from IDLE, you can do:

>>> import os
>>> os.chdir('C:\\Users\\You\\Some\\Arbitrary\\Path')
>>> import scriptname

Keep in mind that you will need to call constructors with scriptname. prepended, like scriptname.myClass(...)

If you change something in the script, you will need to reload it like this:

>>> import imp
>>> imp.reload(scriptname)

(There is a simpler way if you just want to play around with types from one script, and if the script only contains function and class definitions (no running code). Then you can simply open the script in IDLE and go to Run>Run Module. When you use this method, it is not necessary to put scriptname. before constructors.)

Justiciable answered 26/7, 2015 at 21:54 Comment(0)
H
1

In the working directory, myscript.py:

import math as ma

def A_sphere(r):
    return 4 * ma.pi * r**2

r = 6700000 # r_Earth_meters

i = 0
while i < 100000:
    i += 1


python3 # idle

>>> from myscript import *  # will run any code in the script
>>> i
100000
>>> radius = r
>>> A_sphere(radius)
598284904949640.2
>>>
>>> print(ma.pi)
3.141592653589793

Hypocaust answered 8/12, 2022 at 6:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.