I was working on a Python script, and wanted to access Atom's current working directory in that script.
Atom is built on electron.js, and the way you do it in JavaScript is:
let filePath = atom.workspace.getActiveTextEditor().getPath();
I want this variable (simply the directory) in my Python script instead.
The idea of what you're trying to achieve is giving me some headaches. While it's certainly possible to invoke the Python interpreter from JavaScript, it's probably not the best user experience for people using your package.
Before even running the Python script, the package needs to check at least the following:
user has the correct version of Python installed
python is exposed to the PATH
the active file is eligible to be interpreted by Python
These are different problems, but nevertheless some you need to sort out.
You haven't specified, whether you invoke the Python script within a synchronous or asynchronous function. I'm going to assume the former since it's easier to follow for JavaScript beginners, but you might want to change that in a later step
JavaScript
// Import Node's spawn method
const { spawnSync } = require('child_process');
// Get path of active file
const activeEditorPath = atom.workspace.getActiveTextEditor().getPath();
// Spawn child process
const child = spawnSync('python', ['path/to/your/script', activeEditorPath]);
Python
import sys
# Get argument
active_editor_path = sys.argv[1]
# Print editor path
print(f'Active editor path: {active_editor_path}')
Related
I have a react app that loads data from a local json file using
import data from './data.json'
it is all working fine without any issues and I'm able to open my index.html in 3000 and also open it as simple HTML page in browser.
Now I run npm run build which creates the build directory. However, my json values become kind of stagnant as it is hardcoded in the javascript in the build. So the question is how can my code in build directory reads json files from a specific location dynamically.
My question: Why not use fetch and serve the JSON from a server side API?
To partially answer your question:
Without changing any webpack configuration, you can use the import() function, instead of import, and a chunk will be built with the json content within a js file.
async function fn() {
const json = await import("./foo.json")
document.title = json.bar
}
On the other hand, probably, webpack has a way to configure this output to be json, but for that you'll need to npm run eject or use a tool to override the webpack production config.
Apart from other alternatives, what you're looking for vanilla Javascript is called fetch API. It's possible to read from either local or remote URLs via fetch method.
As per the example you provided above, instead of doing below;
import data from './data.json'
You can make use of it like;
fetch('./data.json')
Also it works pretty same way as per any URL;
// Sample working URL example to mock some real data
fetch('https://jsonmock.hackerrank.com/api/football_competitions?year=2015')
And best part of it, the parameter fetch method accept can be modified easily since it both accepts local file path and a URL as a variable very same way;
let baseURL = 'https://jsonmock.hackerrank.com/api',
endpointToCall = 'football_competitions',
year = '2015',
URL;
URL = `baseURL/${endpointToCall}?year=${year}`;
fetch(URL);
Note: With the last example above, my point is to destructure the same API endpoint used with previous example before, via dynamic variables in order to being able to more clearer. Please let me know if it's not and you need more clarification.
What you can do it before you run the npm run build you make a request to your server to get the data.json file and then just run the npm run build when it loads. You can write a simple script for it.
For example:
#!/bin/bash
# Get the file from the server
curl https://yourServer/data.zip -o data.zip
# Unzip the file, you can also use unzip
zip -d data.json
# Move the file to the desired directory
mv data.json /yourApp/data/data.json is
# Navigate to the directory where the npm package is
cd /yourApp/
# This one is optional but you should run a test to see if the app won't crash with the new json data that you fetched
# Run tests
npm run tests
# Run the build command for React
npm run build
You can modify this script with your paths and it should work.
Summary
Get the json data with curl
Unzip it
Move it to your react app where data.json is and replace it
Run the tests (optional)
Run the build
You're done.
Hope this helps.
I am trying to call a function in a python file from a js file, I got this to work through my console, but I am now trying to implement it in a mobile app using expo.
The way I had set this up is, I have the JS file for a certain screen in my app, this then calls a function in a separate JS file, which then calls the function in the python file.
I am using the child_process module to talk to python from JS.
And as I said, this was working before I tried to export the JS function to my screen file.
index.js
export function foo(process, sentence){
const spawn = require("child_process").spawn;
const process = spawn("python3", ["./python.py", sentence]);
...
}
screen.js
*other imports
import { foo } from "./filepath..."
...
But when I run npm start I get the following error:
Failed building JavaScript bundle.
While trying to resolve module `child_process` from file `/Users/mee/Documents/GitHub/project/app/screens/screen.js`, the package `/Users/mee/Documents/GitHub/project/node_modules/child_process/package.json` was successfully found. However, this package itself specifies a `main` module field that could not be resolved (`/Users/me/Documents/GitHub/project/node_modules/child_process/app/screens/screen.js`. Indeed, none of these files exist:
How can I fix this?
It won't work for few reasons
child_process is part of the node standard library, it's not available in other environments like react-native or browser
even if above was not true, there is no python3 executable on your phone
python.py file from your local directory wouldn't be even uploaded to the phone because bundler is only uploading one big js file with entire js code combined + assets, python.py is neither of those.
Only solution that make sense it to rewrite that code to javascript.
Technically it's not impossible, there might be a way to do that, by compiling python interpreter for mobile platform, or using some tool that translates python code into js, but it's not something that you should consider.
I know that this question could be a duplicate of many similar existing questions however, still want to ask more precisely for help in the scenario I want to understand:
I am using this repo in my example and I have following script block in my package.json
I need to pass one parameter from the command line to identify the environment in which I wish to test, for example something like:
-- testEnv=staging
How can I update the following script blcok to accomodate this change.
I have already tried to set different configurations for world parameter like this:
--world-parameters \"{\\\"environment\\\": \\\"Dev\\\"}\"
however it is now confusing to maintain various version of world parameter configs hence looking to use command line to send variable values through.
"scripts": {
"test-chrome": "./node_modules/.bin/cucumber-js.cmd --tags #Run --format json:./testlab/support/reports/report.json",
}
TestCafe allows you to use environment variables, and have a config.json file to store the baseUrl:
So, you could do
export testEnv=staging
npm run test-chrome
Then enter that value as part of your config file.
{
baseUrl: process.env.testEnv
}
Or, if you want a default baseUrl, you could have a helper class that just returns const targetUrl = process.env.testEnv || config.baseUrl.
Starting with version 1.20.0, TestCafe offers a way to specify the base url for test pages in all interfaces:
CLI
Program API runner.run({baseUrl})
Config file
I have an application where the output is written into a file (.py) by using javascript.
I'm using this application to write python script into the file. Now I want to run the python script automatically on cmd(Windows) right after the output was written.
Is there a way to do so ? Is it possible without using "NodeJS"
So apparently everything happens with a single click on the application.
Thanks.
Node js provides the child process module,
which you can use to basically spawn a child process from your js application.
since you have not shared any source code so i am not sure what your specific use case is but a basic way of spawning python script would be like this.
import { spawn } from 'child_process';
let scriptPath = './script.py' // path to your python script
var script = spawn('python', ['-u', scriptPath, arg1, arg2]); // arg1,arg2 can be any command line arguments required by your script or if not needed you can skip them.
script.stdout.on('data', data => {
console.log('Data: ', data.toString());
// implement your functionality here
});
you can similary bind on close and error events to your script and implement the functionality accordingly.
Why not storing your script in a script.py file? Why do you use .txt at all? With CMD and Python installed you should easily run .py scripts with a command line "python path/to/script.py", shouldn't you?
Edit: For checking out how to execute python on Node JS just use Google! Google is your friend! "execute python with node js" threw me this article: How to call python script from NodeJs
Let's say I need CasperJS to report progress steps to a localhost server. I couldn't user casper.open to send a POST request because it'd "switch" pages so to speak and would be unable to continue other steps properly.
I sidestepped this issue by evaluating an XMLHttpRequest() inside the browser to ping to localhost. Not ideal but it works.
As the number of the scripts grow, I'd rather move this common functionality into a module, which is to say, I want to move a number of functions into a separate module.
It's my understanding CasperJS doesn't work like node.js does so require() rules are different. How do I go about accomplishing this?
Since CasperJS is based on PhantomJS you can use its module system, which is "modelled after CommonJS Modules 1.1"
You can require the module file by its path, full or relative.
var tools = require("./tools.js");
var tools = require("./lib/utils/tools.js");
var tools = require("/home/scraping/project/lib/utils/tools.js");
Or you can follow node.js convention and create a subfolder node_modules/module_name in your project's folder, and place module's code into index.js file. It would then reside in this path:
./node_modules/tools/index.js
After that require it in CasperJS script:
var tools = require("tools");
Module would export its functions in this way:
function test(){
console.log("This is test");
}
module.exports = {
test: test
};