How to extract "$" by jsonpath? - python

I'd like to extract an elememt by "$". But it retrieves nothing (the 1st call of main.py). Does anybody know what is wrong? Thanks.
$ cat data.json
{
"id": {
"$": {
"view": "all",
"id": "sec4",
"role": "materials-methods"
}
}
}
$ cat main.py
#!/usr/bin/env python
# vim: set noexpandtab tabstop=2 shiftwidth=2 softtabstop=-1 fileencoding=utf-8:
import sys
import json
json_data = json.load(sys.stdin)
import jsonpath_rw_ext
res = jsonpath_rw_ext.match(sys.argv[1], json_data)
for match in res:
print match.keys()
$ < data.json ./main.py '$."$"'
$ < data.json ./main.py '$."id"'
[u'$']

The right jsonpath expression to use would be '$.id.$'.
Note: Please don't use Python2 for new code and migrate existing Python2 code to Python3

Try this one
$[?(!#.$)]
This ignores all the nodes containing $

Related

Check if your JSON validator in python output True or False

Hi im using the python lib "from jsonschema import validate"
When I using it with it seems it's working I guess but, how can I get a confirm in my CLI when I'm executing this script.
Python file
from jsonschema import validate
import yaml
yaml_schema = open("test.yaml", "r")
json_schema = open("test.json", "r")
validate(yaml.full_load(json_schema.read()), yaml.full_load(yaml_schema.read())) # passes
test.yaml file
type: object
properties:
testing:
type: array
items:
enum:
- this
- is
- a
- test
test.json
{
"testing": ["this", "is", "a", "test"]
}
how can I get a confirm from the terminal, has someone a method for me

Ansible Dynamic Inventory - "([Errno 2] No such file or directory:"

Situation: I am getting an issue when trying to load a basic dynamic inventory python file in Ansible.
Background: When I perform python test.py it will output the list however in ansible it fails
Assessment: I have tried lots of other example files and none have worked, this is the simplest i could make it
Recommendation: Can someone please point me in the right direction? is this to do with the ansible.cfg?
vagrant#cd98f180bc88 /vagrant/adc-cmdb-inventory/enviroments $ python test.py --list
{"all": {"hosts": ["192.168.28.71", "192.168.28.72"], "vars": {"ansible_python_interpreter": "/usr/bin/python3", "ansible_ssh_private_key_file": "~/.vagrant.d/insecure_private_key", "example_variable": "value", "ansible_user": "vagrant"}}, "_me
ta": {"hostvars": {"192.168.28.72": {"host_specific_var": "bar"}, "192.168.28.71": {"host_specific_var": "foo"}}}}
ISSUE:
Command used:
ansible -i test.py all -m ping --list-host
[WARNING]: * Failed to parse /vagrant/adc-cmdb-inventory/enviroments/test.py with script plugin: problem running /vagrant/adc-cmdb-inventory/enviroments/test.py --list ([Errno 2] No such file or directory: '/vagrant/adc-cmdb-
inventory/enviroments/test.py': '/vagrant/adc-cmdb-inventory/enviroments/test.py')
[WARNING]: * Failed to parse /vagrant/adc-cmdb-inventory/enviroments/test.py with ini plugin: /vagrant/adc-cmdb-inventory/enviroments/test.py:4: Expected key=value host variable assignment, got: os
[WARNING]: Unable to parse /vagrant/adc-cmdb-inventory/enviroments/test.py as an inventory source
[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'
hosts (0):
test.py
#!/usr/bin/python
# -*- coding:utf-8 -*-
import os
import sys
import argparse
import json
class ExampleInventory(object):
def __init__(self):
self.inventory = {}
self.read_cli_args()
# Called with `--list`.
if self.args.list:
self.inventory = self.example_inventory()
# Called with `--host [hostname]`.
elif self.args.host:
# Not implemented, since we return _meta info `--list`.
self.inventory = self.empty_inventory()
# If no groups or vars are present, return empty inventory.
else:
self.inventory = self.empty_inventory()
print(json.dumps(self.inventory))
# Example inventory for testing.
def example_inventory(self):
return {
'all': {
'hosts': ['192.168.28.71', '192.168.28.72'],
'vars': {
'ansible_user': 'vagrant',
'ansible_ssh_private_key_file':
'~/.vagrant.d/insecure_private_key',
'ansible_python_interpreter':
'/usr/bin/python3',
'example_variable': 'value'
}
},
'_meta': {
'hostvars': {
'192.168.28.71': {
'host_specific_var': 'foo'
},
'192.168.28.72': {
'host_specific_var': 'bar'
}
}
}
}
# Empty inventory for testing.
def empty_inventory(self):
return {'_meta': {'hostvars': {}}}
# Read the command line args passed to the script.
def read_cli_args(self):
parser = argparse.ArgumentParser()
parser.add_argument('--list', action = 'store_true')
parser.add_argument('--host', action = 'store')
self.args = parser.parse_args()
# Get the inventory.
ExampleInventory()
Invisible Line endings!
I ended up installing dos2unix and converting the files there were CR and LF tags at the end of each line.
Remove the CF lines with dos2unix and it working first time.
https://imgur.com/AN8ACWC

Call a Python script from another Python script with list as argument?

I am trying to run a Python script a.py from another Python script scheduler.py and I want to pass a list as argument something like:
Scheduler.py:
t = {"code": 161123134, "name": "task2", "domain": "www.google.com", "type": "Type1", "keywords": ["bai2", "yin4", "jiao3", "yi8", "ping1", "tai3"]}
hourTasks = json.dumps(t)
os.system("python a.py " + hourTasks)
a.py
task = sys.argv[1:]
task = json.loads(task)
However It gives me an error the JSON object must be str, bytes or bytearray, not 'list'. Anyone know what the problem is?
Try this:
Scheduler.py:
import json
import subprocess
t = {"code": 161123134, "name": "task2", "domain": "www.google.com", "type": "Type1", "keywords": ["bai2", "yin4", "jiao3", "yi8", "ping1", "tai3"]}
task = json.dumps(t)
subprocess.call(["python", "a.py", task])
a.py:
import json
import sys
task = sys.argv[1]
t = json.loads(task)
from one script you should import the other and there is no need to use json between your two scripts, just pass an python dict instead.
You could use the method of the dicts, to read the keys and the values. And before that do a counter and membership check like. For x in xs:

Running a Python program from Go

I have written some code in Python that uses some libraries that are not in Go. I have a web server that I have written in Go and I would like to be able to call a Python program from my Go program and then use the output of the Python program as input in my Go program. Is there anyway to do this?
It's actually relatively easy. All you need to do is use the os/exec library. Here is an example below.
Go Code:
package main
import (
"fmt"
"os/exec"
)
func main() {
cmd := exec.Command("python", "python.py", "foo", "bar")
fmt.Println(cmd.Args)
out, err := cmd.CombinedOutput()
if err != nil { fmt.Println(err); }
fmt.Println(string(out))
}
Python Code:
import sys
for i in range(len(sys.argv)):
print str(i) + ": " + sys.argv[i]
Output From Go Code:
[python python.py foo bar]
0: python.py
1: foo
2: bar

Replace string in Python and open browser with result

I am trying to build a plugin for the program Sublimetext2.
It uses plugins coded with Python. I have no Python knowledge at all but from looking at existing plugins and my PHP knowledge here is what I need help with...
this is the start of the Python file so far
import sublime, sublime_plugin
import webbrowser
settings = sublime.load_settings('openonserver.sublime-settings')
settings.get('file_path_prefix')
settings.get('server_url')
class OpenonServerCommand(sublime_plugin.TextCommand):
def run(self,edit):
file_path = self.view.file_name()
What I need to do though take the value of the settings
file_path will be the path to the file I am running this on so lets say...
E:\Server\htdocs\mytest_project_\some\folder_\test.php
The settings
file_path_prefix will be E:\Server\htdocs\ and
server_url will be http://localhost/
I need to see if file_path_prefix exist in file_path if it does,
I need to replace the E:\Server\htdocs\ with the http://localhost/ and replace all \ to / and then store this new path in a variable
so...
E:\Server\htdocs\mytest_project_\some\folder_\test.php would become
http://localhost/mytest_project_/some/folder_/test.php
I then need to send this to the browser.
Any help is greatly appreciated
Use
os.system("path_to_browser url")
To run any external program. I also recomend to take a look at this comment
Ok after many hours (I hate Python now) my solution (i'm very not impressed) but it partially works
#Context.sublime-menu
[
{ "command": "openserver", "caption": "Open on Server" }
]
#Default (Windows).sublime-keymap
[
{ "keys": ["ctrl+shift+b"], "command": "openserver" }
]
#Main.sublime-menu
[
{
"caption": "Tools",
"mnemonic": "T",
"id": "tools",
"children":
[
{ "command": "openserver", "caption": "Open on Server" }
]
}
]
#Openserver.sublime-commands
[
{
"caption": "Open file on Server in Browser",
"command": "openserver"
}
]
#Openserver.sublime-settings
{
"file_path_prefix": "E:/Server/htdocs",
"url_prefix": "http://localhost"
}
Main file
#openserver.py
import sublime, sublime_plugin
import os
import webbrowser
import re
import os2emxpath
import logging
import sys
class OpenserverCommand(sublime_plugin.TextCommand):
def run(self,edit):
file_path = self.view.file_name()
settings = sublime.load_settings('Openserver.sublime-settings')
file = os2emxpath.normpath(file_path)
url = re.sub(settings.get('file_path_prefix'), settings.get('url_prefix'), file)
#logging.warning(url)
#webbrowser.open_new(url)
if sys.platform=='win32':
os.startfile(url)
elif sys.platform=='darwin':
subprocess.Popen(['open', url])
else:
try:
subprocess.Popen(['xdg-open', url])
except OSError:
logging.warning(url)
Now when I say it works but it partially doesn't, it does take the file name, replaces my path and server URL from a settings file and then does launch a browser with the proper URL
Except, in Sublimetext2 when you run this on a .py file or any file that you do not have set to be able to open in a web browser, then instead of opening the file in the web browser it will give the windows popup asking to set a default program to open the file, very annoying!

Categories