An ipython notebook is a document that is read by the browser that contains both rich text and python code.
In scientific computing ipython notebooks are often used to perform an analysis some input data file that resides on the local file system.
Instead of manually pasting the full path of the file containing the data into a variable, would be convenient to be able to launch an open-file dialog in order to browse the local file system and select the file. The full path of the file should be returned in a variable (in python).
This can be achieved launching an open-file dialog from a GUI toolkit (i.e. QT). For an example see IPython Notebook: Open/select file with GUI (Qt Dialog).
However, using QT has some disadvantages. First it is an additional dependency. Second it requires enabling the QT gui integration in the notebook and this results in conflicts with the inline plots (see here).
The question here is, is it possible to obtain the full path using only Javascript?
EDIT: The answer posted below only returns the file name, not the full-path.
Using the HTML5 construct <input type="file"> is possible to instruct the browser to open a file selector dialog. Then we need to bind a javascript function to the "changed event".
The javascript can use kernel.execute(command) to execute a command on the python kernel that assign a variable with the selected file path.
Here an example:
input_form = """
<div style="border:solid navy; padding:20px;">
<input type="file" id="file_selector" name="files[]"/>
<output id="list"></output>
</div>
"""
javascript = """
<script type="text/Javascript">
function handleFileSelect(evt) {
var kernel = IPython.notebook.kernel;
var files = evt.target.files; // FileList object
console.log('Executing orig')
console.log(files)
// files is a FileList of File objects. List some properties.
var output = [];
var f = files[0]
output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
f.size, ' bytes, last modified: ',
f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
'</_Mli>');
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
var command = 'fname = "' + f.name + '"'
console.log(command)
kernel.execute(command);
}
document.getElementById('file_selector').addEventListener('change', handleFileSelect, false);
</script>
"""
def file_selector():
from IPython.display import HTML, display
display(HTML(input_form + javascript))
After the previous definitions putting in a cell file_selector() will display a button "Choose file" and after a file is selected the variable fname in the notebook will contain the file path.
References
http://www.html5rocks.com/en/tutorials/file/dndfiles/
https://jakevdp.github.io/blog/2013/06/01/ipython-notebook-javascript-python-communication/
this other StackOverflow
"How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?"
has already cleared the question : you can't get local fullpath from HTML (5 or previous) interface due to security politic.
So it is normal that you need QT (or equivalent) to get what you need.
I've been searching a Flash equivalent, but it seems that you may only have it with AIR according to this StackOverflow :
"Flex - How to browse and get the full path of a file on local machine's file system?"
Related
So, after having not programmed for 23 years, I decided to start learning Javascript.
I am trying to write a program to read through my music files and create a HTML page based on the files found in a specific directory.
It goes well until I hit filenames containing diacritics in it (like é, ü, ø etc).
For Example: André Hazes turns into : André Hazes
For Example: Andrea Bocelli & Sarah Brightman - Time to Say Goodbye [Con Te Partirò] (single) turn into Andrea Bocelli & Sarah Brightman - Time to Say Goodbye [Con Te PartiroÌ€] (single)
The link I have created doesn't work anymore
The command I use to create the HTML statement is:
<td>${item.vFilename}</td>
This is the code I use to read the files from the filesystem. I work on a Mac, OS Catalina, so basically an Unix variant.
// List all files in a directory in Node.js recursively in a synchronous fashion
var ReadDirFiles = function(pdir, pfilelist) {
files = vFileSystem.readdirSync(pdir,"utf-8");
filelist = pfilelist;
files.forEach(function(file) {
if (vFileSystem.statSync(pdir + '/' + file).isDirectory()) {
filelist = ReadDirFiles(pdir + '/' + file, filelist);
}
else {
vstats = vFileSystem.statSync(pdir + '/' + file);
// debug info
// console.log(vstats);
filelist.push({vFilename: file, vDir: pdir, vBirthtime: formatDate(vstats.birthtime), vSize: vstats.size});
}
});
return filelist;
};
This is the statement I use to write the output to disk and it turns out the problem is in the write statement:
fs.writeFileSync(buildPathHtml.buildPathHtml(), html);
When the output is written back to disk, the conversion of the diacritics happens.
Anyone knows the trick how to work diacritics?
Try using encoding and decoding functions in your script. There are many functions doing this in Javascript, just use what you need. For a complete encoding/decoding you can use (or only copy & paste) into your script the code suggested in https://www.strictly-software.com/htmlencode/. There is a little encoding Javascript library doing the job (encoder.js).
Maybe your file system isn't utf8 based. I read somewhere it's Western for Mac.
I'm calling an Applescript scpt file and when I opened the AppleScript editor it had an option to use JavaScript.
I would like to convert my AppleScript to JavaScript but can't find any documentation on it (announcements and such and redirects on apple).
Here is my AppleScript:
#!/usr/bin/osascript
on run argv
set output to "{\"1st Parameter\":\"" & first item of argv & "\"}"
return output
end run
More context:
I'm trying to loop through a directory and export from Excel. I only need to know about how to run JavaScript in a SCPT file but this is the background.
#!/usr/bin/osascript
on run argv
#goal is to export multiple files to csv
#the plan is to
#pass in folder and loop through files or
#pass in array of files (paths as a comma separated string)
#pass in single file and call script multiple times
set processReportsScript to "excel -e '" & first item of argv & "' '" -o '" & second item of argv & "'.csv'"
do shell script processReportsScript
end run
UPDATE:
While in Script Editor I'm able to run this JavaScript:
function run(args) {
var x = false;
var y = Application("Mail");
var running = y.running();
var id = y.id();
debugger;
if (x) {
console.log("Why isn't this being called?")
}
return "hello";
}
Based in part on this guide.
However when I save the JavaScript into the SCPT file and call it from an external application it gives the following error:
script error: Expected end of line, etc. but found “(”. (-2741)
It does not give any errors when using AppleScript.
FYI the external application is passing the script to osascript.
UPDATE 2:
I changed the extension from scpt to js and now it's running. I read that it's possible to pass in the language type using -l but when I do I get numerous variations of the error:
no such component " 'JavaScript'"
no such component " JavaScript"
As long as it works by changing the extension I think this works.
Both AppleScript and JavaScript for Automation (JXA) use the same file extension: ".scpt". When you are in the Script Editor, there is a language popup where you can select either:
The is no tool for auto-conversion from AppleScript to JXA.
For more info about JXA, see
JXA Resources
I have a Javascript program that extracts data from a text file (just a plain *.txt file) and then displays it in a table. It works as intended except for one issue: If I update the text file where the data lives in the update does not shows up on the table. The reason is that the file is being cached by the browser.
Is there a way to force Javascript to read from the latest version of the file and not from the cached version? Again, this is not a problem with the javascript file as doing Ctrl-5 and or Shift+Ctrl+R does not works and also updating the javascript file itself behaves as expected. it is only the file where the data is in that is the problem.
To read the text file I use the Webix toolkit which uses AJAX to read the file. The reading and parsing of the text file is done via Javascript and the Webix toolkit. There is very little html in my program.
//the name of the file is dependant of an user specified input
var theURL = rossObj.store_number.store_number + "macaddress.txt ";
webix.ajax(theURL,{
//response
error:function(text, xml, XmlHttpRequest){
webix.alert({ ok:"OK", type:"alert-warning", text:"could not open the following URL --> "+theURL, width:"400px"});
return "mac_address_error";
},
success:function(text, xml, XmlHttpRequest){
//parse the file;
}
});
Try adding a random number to the end of the url as a query string, the server will ignore but the browser will treat it as a new file
var theURL = rossObj.store_number.store_number +
"macaddress.txt?" +
Math.floor((Math.random() * 10000) + 1);
I am working on a project which must be self contained and able to run without an internet connection. It's is for video presentations and I need to import a .txt file which includes chapters and loop information such as Chapter Title, Looping point and chapter end point (both in frames). However, there is no client-side include script to include a text file.
What would be the best way for me to store or access a local text file so that I can iterate over it and build my chapters object? HTML5 local storage? Hacking by including a hidden iframe that loads the text file then grab that body content via JavaScript? Any help on this issue would be greatly appreciated.
Thanks!
For your question "Need Access to Local Text File via JavaScript" is very similar to this question here: Local file access with javascript
The Answer is there really isn't a good way to access a local file if you are using javascript in a browser. If its just a text file on the same machine without a http/webserver you may run into some problems, as in javascript the ability to read a local file is disabled by default in most browsers. In chrome you can disable this security-feature by adding the following flag when starting the browser from command-line.
--disable-web-security
If your data is structured json, xml, csv, you can bring it in using an AJAX call if the file is hosted on a server accessible with HTTP. Without using an http ajax call, another possible solution as mentioned in the question link above:
Just an update of the HTML5 features http://www.html5rocks.com/en/tutorials/file/dndfiles/
This excellent article will explain en detail the local file access in
Javascript. Summary from the mentioned article:
The spec provides several interfaces for accessing files from a
'local' filesystem:
File - an individual file; provides readonly information such as name,
file size, mimetype, and a reference to the file handle. FileList - an
array-like sequence of File objects. (Think or dragging a directory of files from the desktop). Blob -
Allows for slicing a file into byte ranges.
-- #Horst Walter
As shown below you can have a "file upload" input selection, and simply have your file path as a default option for the input"
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
f.size, ' bytes, last modified: ',
f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
'</li>');
}
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
You can use AJAX to read the text file.
with javascript you can't edited, you can only read it.
an example will be :
1- create a text file "page.txt"
2- create a html page with this code
<!DOCTYPE html>
<html>
<body>
<script>
text = new XMLHttpRequest();
text.open("GET","page.txt",false);
text.onload = function(){
document.write(text.responseText);
}
text.send();
</script>
</body>
</html>
Is there a possible way to read a local file in JavaScript.
MyFolder:
db.csv
Parse.js
Trying to fetch the contents of file db.csv in Parse.js, But in vain.
Can you share some links where I can get enough knowledge how to read a file.
Running Instruments in Xcode5, with test scripts in .js file where I have to feed in some values from a .csv file.
iOS UIAutomation, apple provides an api for running a task on the target's host.
performTaskWithPathArgumentsTimeout
Using this, we can have a bash script to printout the contents of a file that we wanted to fetch in the first case.
Bash script can be as simple as this for this requirement.
#! /bin/bash
FILE_NAME="$1"
cat $FILE_NAME
Save it as for example FileReader.sh file.
And in your automation script,
var target = UIATarget.localTarget();
var host = target.host();
var result = host.performTaskWithPathArgumentsTimeout(executablePath,[filePath,fileName], 15);
UIALogger.logDebug("exitCode: " + result.exitCode);
UIALogger.logDebug("stdout: " + result.stdout);
UIALogger.logDebug("stderr: " + result.stderr);
where in,
executablePath is where the command need to be executed.
var executablePath = "/bin/sh";
filePath is the location of the created FileReader.sh file. When executed, outputs the content to standard output (in our requirement).
[give full absolute path of the file]
fileName is the actual file to fetch contents from.
[give full absolute path of the file] In my case I had a Contents.csv file, which I had to read.
and the last parameter is the timeout in seconds.
Hope this helps others, trying to fetch contents (reading files) for performing iOS UIAutomation.
References:
https://stackoverflow.com/a/19016573/344798
https://developer.apple.com/library/iOS/documentation/UIAutomation/Reference/UIAHostClassReference/UIAHost/UIAHost.html
If the file is on the same domain as the site you're in, you'd load it with Ajax. If you're using Ajax, it's be something like
$.get('db.csv', function(csvContent){
//process here
});
Just note that the path to the csv file will be relative to the web page you're in, not the JavaScript file.
If you're not using jQuery, you'd have to manually work with an XmlHttpRequest object to do your Ajax call.
And though your question doesn't (seem to) deal with it, if the file is located on a different domain, then you'd have to use either jsonP or CORS.
And, just in case this is your goal, no, you can't, in client side JavaScript open up some sort of Stream and read in a file. That would be a monstrous security vulnerability.
This is a fairly simple function in Illuminator's host functions library:
function readFromFile(path) {
var result = target.host().performTaskWithPathArgumentsTimeout("/bin/cat", [path], 10);
// be verbose if something didn't go well
if (0 != result.exitCode) {
throw new Error("readFromFile failed: " + result.stderr);
}
return result.stdout;
}
If you are using Illuminator, this is host().readFromFile(path).