Skip to content

Instantly share code, notes, and snippets.

@bnmnetp
Last active October 15, 2023 09:11
  • Star 24 You must be signed in to star a gist
  • Fork 20 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save bnmnetp/4650616 to your computer and use it in GitHub Desktop.
Here is about the simplest example I can think of that gets you a working skulpt environment. This little sample shows regular python as well as importing a module.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js" type="text/javascript"></script>
<script src="http://www.skulpt.org/js/skulpt.min.js" type="text/javascript"></script>
<script src="http://www.skulpt.org/js/skulpt-stdlib.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
// output functions are configurable. This one just appends some text
// to a pre element.
function outf(text) {
var mypre = document.getElementById("output");
mypre.innerHTML = mypre.innerHTML + text;
}
function builtinRead(x) {
if (Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined)
throw "File not found: '" + x + "'";
return Sk.builtinFiles["files"][x];
}
// Here's everything you need to run a python program in skulpt
// grab the code from your textarea
// get a reference to your pre element for output
// configure the output function
// call Sk.importMainWithBody()
function runit() {
var prog = document.getElementById("yourcode").value;
var mypre = document.getElementById("output");
mypre.innerHTML = '';
Sk.pre = "output";
Sk.configure({output:outf, read:builtinRead});
(Sk.TurtleGraphics || (Sk.TurtleGraphics = {})).target = 'mycanvas';
var myPromise = Sk.misceval.asyncToPromise(function() {
return Sk.importMainWithBody("<stdin>", false, prog, true);
});
myPromise.then(function(mod) {
console.log('success');
},
function(err) {
console.log(err.toString());
});
}
</script>
<h3>Try This</h3>
<form>
<textarea id="yourcode" cols="40" rows="10">import turtle
t = turtle.Turtle()
t.forward(100)
print "Hello World"
</textarea><br />
<button type="button" onclick="runit()">Run</button>
</form>
<pre id="output" ></pre>
<!-- If you want turtle graphics include a canvas -->
<div id="mycanvas"></div>
</body>
</html>
@saibotshamtul
Copy link

saibotshamtul commented Oct 11, 2016

@Carcabob Yes, it can be done, if, at the bottom of the page, you add Javascript code that calls the runit function, it should run the code when the page loads. You can combine this with making the textbox display:none to hide it, and it should work how you want.

For example: http://codepen.io/saibotshamtul/full/LRmpmm/

@Amarix
Copy link

Amarix commented Jul 10, 2017

Thank you!!

@reganarntzgray
Copy link

Hi, I am very new to programming. I am learning python and have created an interactive blackjack game that I wanted to share on my squarespace website. I tried posting in the gist on a squarespace code block and the run button and python text showed up but there is nowhere for the output to show up and nothing happens when I click run. Any advice?

Thanks!!
Regan

@GraniteConsultingReviews

I am trying this code but this is not working I have a problem in script which is not giving proper result.

@bnmnetp
Copy link
Author

bnmnetp commented Sep 4, 2017

If I download the gist and bring it up in my browser it runs the example just fine. I don't know how to help you GraniteConsultingReviews because you haven't given me any information on what you are trying to do or what kind of script you are trying to run or even what is going wrong.

@Solomon1984ustc
Copy link

when I copy skulpt.min.js and skulpt-stdlib.js to the local, they donnot work,why?

@prescod
Copy link

prescod commented Feb 5, 2018

I'm skeptical that line 33 is necessary:

Sk.pre = "output";

It seems to duplicate the role of the outf function.

It seems to work for me when I comment it out.

@bnmnetp
Copy link
Author

bnmnetp commented Feb 5, 2018

It will work fine if that is the only instance of skulpt on the page. This may be totally left over, but it is important that we can have multiple instances of skulpt running on the page each with their own distinct output, and early on, if I recall correctly, this was a way to handle that. I never committed to making this a minimal perfect gist.

@edips
Copy link

edips commented Dec 8, 2018

Thank you. This is the best documentation for understanding skulpt.

@mukarharprit
Copy link

Can Skulpt support numpy, pandas and matplotlib modules?

@thlengane
Copy link

I have tried "import os" but it doesn't seem to accept it, how can I get around this?

@christiantakle
Copy link

christiantakle commented Apr 11, 2020

Hi I was trying to teach a friend some javascript and he was using skulpt. I are quite many anti-patterns used in the above I rewrote it with him while explaining the what/why. Note I'm using newer browser features like ?. and arrow-functions so will only work in evergreen browsers. However I assume most people will work in a package.json env using some form of transpiler.

I will just leave the snippet here incase you want to use some if it. You can dial back the features used but newer ordering make more sense.

Notes:

  • jquery isn't used just confuse people that its imported.
  • Sk.pre = "output"; @ line 33 what is this doing it make no sense and code runs fine without it.
  • import the script at the end of the body this mean that the html is present when document.get... is called so the references can be cache and its easier to spot the moving parts.
  • type="text/javascript" not needed in html:5
<html>
  <head>
    <script src="http://www.skulpt.org/js/skulpt.min.js"></script>
    <script src="http://www.skulpt.org/js/skulpt-stdlib.js"></script>
  </head>

  <body>
    <h3>Try This</h3>
    <form>
      <textarea id="skulpt--input" cols="40" rows="10">
import turtle

t = turtle.Turtle()
t.forward(100)

print "Hello World" 
</textarea
      ><br />
      <button type="button" onclick="skulptMain()">Run</button>
    </form>
    <pre id="skulpt--output"></pre>
    <div id="skulpt-canvas--output"></div>
    <script>
      const inputRef = document.getElementById("skulpt--input");
      const outputRef = document.getElementById("skulpt--output");

      function skulptMain() {
        outputRef.innerHTML = "";
        Sk.configure({
          output: (text) => {
            outputRef.innerHTML = outputRef.innerHTML + text;
          },
          read: (file) => {
            if (Sk.builtinFiles?.["files"][file] === undefined) {
              throw `File not found: '${file}'`;
            }
            return Sk.builtinFiles["files"][file];
          },
        });

        (Sk.TurtleGraphics || (Sk.TurtleGraphics = {})).target =
          "skulpt-canvas--output";

        Sk.misceval
          .asyncToPromise(() =>
            Sk.importMainWithBody("<stdin>", false, inputRef.value, true)
          )
          .then(
            (mod) => console.log("success"),
            (err) => console.log(err.toString())
          );
      }
    </script>
  </body>
</html>

@Sachin5411
Copy link

Hi , i want to add other python libraries like numpy , matplotlib, sklearn into the skulpt...
Can you please tell me if this is possible and how?

thank you

@bnmnetp
Copy link
Author

bnmnetp commented Apr 21, 2020

skulpt is an implementation of Python in Javascript. It runs completely in the browser. Much of bumpy, matplotlib and sklearn are implemented in C or FORTRAN and do not run in the browser, so this is not as easy as you might think. There are some partial implementations of a few things like numpy that others have done.

@NatiThai
Copy link

I have a big problem, I would like to create a function check(Javascript) text form output but I don't know how to create that
I need a solution please help.

Best regards

@mr-douglas
Copy link

mr-douglas commented Jul 11, 2020

This seems to run Python 2, is there a Python 3 version?
(I tried print(6/5) and print 6 / 5 and both seemed to behave like Python 2)

@justinwride
Copy link

This seems to run Python 2, is there a Python 3 version?
(I tried print(6/5) and print 6 / 5 and both seemed to behave like Python 2)

Check out this issue skulpt/skulpt#777

@gracekim-14
Copy link

The example worked well for me but I cannot seem to prompt the user for an input using turtle.textinput().

This is the beginning of my code:

import turtle

screen = turtle.Screen()
screen.setup(width=500, height=400)
user_bet = screen.textinput("Place your bet","Which turtle do you think will win? Enter a colour: ")

And it returns the error:
AttributeError: 'Screen' object has no attribute 'textinput' on line 7

@gracekim-14
Copy link

I have python projects that need to import/modify other files. How can I do this using skulpt?

@SamHastings1066
Copy link

"Uncaught ReferenceError: Sk is not defined skulpt"

To avoid the error above I had to remove the www. from the script URLs. See this stackoverflow answer.

@jhlchan
Copy link

jhlchan commented Oct 15, 2023

Please fix this by replacing the lines:

<script src="http://www.skulpt.org/js/skulpt.min.js" type="text/javascript"></script> 
<script src="http://www.skulpt.org/js/skulpt-stdlib.js" type="text/javascript"></script> 

with these two lines:

<script src="https://skulpt.org/js/skulpt.min.js" type="text/javascript"></script>
<script src="https://skulpt.org/js/skulpt-stdlib.js" type="text/javascript"></script>

This will help people reading Get Started with Skulpt, especially the section Using Skulpt with HTML with an example that works immediately.

Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment