|  | Home If you're new to Python and VPython: Introduction A VPython tutorial Pictures of 3D objects What's new Classic VPython web site VPython license Python web site |  |
Files and Libraries |
# File operations In GlowScript VPython, you can import an external JavaScript library or read a file on the user's local computer. The following information does not apply to Jupyter VPython, where one can use the standard Python methods for importing modules and reading or writing files. # get_library: import a library To import a JavaScript library, do this: get_library("http://xyz.org/lib.js") If the file cannot be found within a reasonable amount of time, an error message is displayed. Currently the library must be written in JavaScript, not RapydScript, or VPython. Moreover, there are restrictions imposed because the library doesn't go through the special preprocessing that occurs when you run your program at glowscript.org. The library cannot include options that require using "rate" or "waitfor", and the following vector operations must be rewritten as shown, where A and B are vectors and k is an ordinary number: A+B -> A.add(B) A-B -> A.sub(B) k*A -> A.multiply(k) A/k -> A.divide(k) However, when editing a file at glowscript.org in any language, clicking "Share this program" outputs code that has been converted to executable JavaScript, so you may find it useful to start from, say, RapydScript or VPython. You may have to make adjustments to the generated JavaScript. It is not currently possible to import from your own glowscript.org files, so the library must be placed on your own web site. # read_local_file: user chooses a file The reading and writing of files is very different in a web browser, due to security issues (you don't want an arbitrary web page to read and write your computer files). You can ask the user of your program to choose a text file on the user's computer and then use the contents of the file. The function read_local_file appends a button that says "Choose File" on the screen at the location specified, such as scene.title_anchor or scene.caption_anchor. When the user clicks that button, a file dialog appears which lets the user choose a file. Then the button is removed, and information about the file is returned. f = read_local_file(scene.title_anchor) print(f.name) # The file name print(f.size) # File size in bytes print(f.type) # What kind of file print(f.date) # Creation date if available print('-------------------') print(f.text) # The file contents If you say read_local_file(), the button is appended to the bottom of the window, corresponding to the jQuery location $('body'). # Writing a file Due to security issues, it is not possible to write directly to the user's computer storage from a browser. Currently the only way to write data to a local file is to print the data, select the print area (ctrl-A), copy (ctrl-C), paste into a local text editor, and save the file.