График не появляется с Matplotlib в Skulpt - PullRequest
0 голосов
/ 25 марта 2020

Во-первых, простите за мой бедный английский sh. Я создал страницу HTML, используя Sculpt с Ace Editor, чтобы использовать код Python на моем веб-сайте. Это работает, но я не могу выполнить функцию с модулем matplotlib следующим образом:

import matplotlib.pyplot as plt
plt.plot([1, 2, 3])
plt.show()

Но модуль Turtle работает нормально!

Вот мой полный код:

	
  <title>Marjorie</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
		    
		
		<style>
            #editor { 
				height: 150px;
			}
			#codeOutput {
				height: 150px;
			}

        </style>

		<!-- script libraries : jquery, bootstrap et skulpt -->
		<script src="external/jquery.min.js"></script> 
		<script src="external/bootstrap.min.js"></script>
		<script src="external/js/skulpt.min.js"></script> 
		<script src="external/skulpt-stdlib.js"></script>
		<script src="external/python.min.js"></script>
		<script src="external/matchbrackets.min.js"></script>

        <script>
        
		// clear the editor window
			function clearAceCode() {
                editor.setValue("");
            }
        </script>
		
		<script type="text/javascript"> 
		// The following scripts are slightly modified versions of the ones on the Skulpt web page  
		
		// output functions are configurable.  This one just appends some text
		// to a pre element.
		
		
		
		function outf(text) { 
			var mypre = document.getElementById("codeOutput"); 
			mypre.innerHTML = mypre.innerHTML + text; 
		} 
		function builtinRead(x) {
			if (Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined)
					throw "Fichier introuvable: '" + 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 = (editor.getValue());
		   prog = S(prog).latinise().s; // TODO: (BAD) workaround for accents/utf-8   
           var mypre = document.getElementById("codeOutput"); 
		   Sk.python3 = true;
		   mypre.innerHTML = ''; 
		   Sk.pre = "codeOutput";
		   Sk.configure({output:outf, read:builtinRead, retainglobals: true}); // 'retainglobals': really cool!
		   //Sk.configure({output:outf, read:builtinRead});
		   Sk.canvas = 'mycanvas';
          (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());
		   });
		   mypre.scrollTop=mypre.scrollHeight;
		}
Sk.externalLibraries = {
   "numpy": {path: 'external/numpy/__init__.js', dependencies: ['external/math/math.js']},
   "matplotlib": {path: 'external/matplotlib/__init__.js'},
   "matplotlib.pyplot" : {path: 'external/matplotlib/pyplot/__init__.js',
                          dependencies: ['external/d3.min.js', 'external/jquery.js']}
}; // matplotlib: use 'plt.show()'
document.onkeydown = function (e) {
  e = e || window.event;
  if (e.ctrlKey && (e.which == 13 || e.keyCode == 13)) {
    set();
    runit(editor_focus); // last codemirror editor which add focus
  }
};		// End of Skulp scripts
		</script> 

    </head>
    
    <body>

			<div class="container">
				<div class="navbar-header">
					
					<a class="navbar-brand" href="#"><b>Madame Diana</b></a>
				</div>
			</div>

		<div class="container">
			
			<!-- put your header here -->
			<h2>       </h2>
			
			
				
         
				<div class="col-sm-8">
					<h4>Fenêtre d'édition</h4>		
					<!-- the editor window -->
					<div id="editor"></div>
					<!-- the editor library is included here along with its set up code -->
					
					<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.1/ace.js"></script>
					<script>
						var editor = ace.edit("editor");
						document.getElementById('editor').style.fontSize='14px';
						//editor.setTheme("ace/theme/monokai");
						//editor.setTheme("ace/theme/solarized_light");
						editor.setTheme("ace/theme/textmate");
						
						editor.getSession().setMode("ace/mode/python");
                    
						// Python code goes here
						code = "def poids(masse): \n  return masse*9.81 \n\nprint(poids(56))\n";

						editor.setValue(code);
					</script>

		        	<button class="btn btn-default" onclick="runit()">Exécuter</button>
					<button class="btn btn-default" onclick="clearAceCode()">Effacer</button>
					<button class="btn btn-default" onclick="editor.setValue(code)">Restaurer</button>
					
					<h4>Sortie :</h4>
					<textarea id="codeOutput" style="width:100%" ></textarea>
				
				</div>
 <div id="mycanvas"></div>
			</div>
		</div> <!-- /container -->  
		    
	</body>	
	

Большинство javascript файлов находятся в локальной папке, поэтому сниппет не может работать правильно ;-)

Если вы поможете мне, я сделаю очень ценю: -)

Заранее спасибо

...