python to jython by execnet doesn't run - python

I'm trying to run a example from http://codespeak.net/execnet/example/hybridpython.html but python freezes on line:
gw = execnet.makegateway("popen//python=jython")
Example:
import execnet
gw = execnet.makegateway("popen//python=jython")
channel = gw.remote_exec("""
from java.util import Vector
v = Vector()
v.add('aaa')
v.add('bbb')
for val in v:
channel.send(val)
""")
for item in channel:
print (item)
I'm on Debian Jessie

If you read the documentation, the following is defined
def makegateway(self, spec=None):
"""create and configure a gateway to a Python interpreter.
The ``spec`` string encodes the target gateway type
and configuration information. The general format is::
key1=value1//key2=value2//...
If you leave out the ``=value`` part a True value is assumed.
Valid types: ``popen``, ``ssh=hostname``, ``socket=host:port``.
Valid configuration::
id=<string> specifies the gateway id
***python=<path> specifies which python interpreter to execute***
execmodel=model 'thread', 'eventlet', 'gevent' model for execution
chdir=<path> specifies to which directory to change
nice=<path> specifies process priority of new process
env:NAME=value specifies a remote environment variable setting.
If no spec is given, self.defaultspec is used.
"""
meaning you should write:
gw = execnet.makegateway("popen//python=C:\\..\\jython2.7.0\\bin\\jython")

Related

How to get default browser name using python?

Following solutions (actually it is only one) doesn't work to me :
How to get a name of default browser using python
How to get name of the default browser in windows using python?
Solution was:
from _winreg import HKEY_CURRENT_USER, OpenKey, QueryValue
# In Py3, this module is called winreg without the underscore
with OpenKey(HKEY_CURRENT_USER,
r"Software\Classes\http\shell\open\command") as key:
cmd = QueryValue(key, None)
But unfortunately, in Windows 10 Pro I don't have targeted registry value. I've tried to find alternative keys in Regedit, but no luck.
Please take a look, what my registry virtually contains:
The following works for me on Windows 10 pro:
from winreg import HKEY_CURRENT_USER, OpenKey, QueryValueEx
reg_path = r'Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice'
with OpenKey(HKEY_CURRENT_USER, reg_path) as key:
print(QueryValueEx(key, 'ProgId'))
Result (first with Chrome set as default, then with IE):
$ python test.py
('ChromeHTML', 1)
$ python test.py
('IE.HTTPS', 1)
Please check for the key in windows 10
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\Shell\Associations\URLAssociations(http|https)\UserChoice
def get_windows_default_browser_launch():
""" On windows, return the default browser for 'https' urls
returns: example '"C:\Program Files\Mozilla Firefox\firefox.exe" -osint -url "%1"'
"""
import winreg
key = winreg.OpenKey(winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER), r"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice")
prog_id, _ = winreg.QueryValueEx(key, "ProgId")
key = winreg.OpenKey(winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE), r"SOFTWARE\Classes\{}\shell\open\command".format(prog_id))
launch_string, _ = winreg.QueryValueEx(key, "") # read the default value
return launch_string
Windows 10 Python3 , may want to change the key for 'http' not https, but this is my code verbatim as my context is of a secured server. I wanted the browser binary name and path, which is just one more line.

Retrieving the netnsid of a network namespace in Python

When trying to find the correct peer network interface of a veth pair that lives in a different namespace, that end is not only indicated by its iflink property, but also by a link-netnsid. This link-netnsid is a network namespace ID which is only meaningful within the current network namespace.
The Linux kernel doesn't offer to map a netnsid to a network namespace inode number, which is the only unique identification. However, Linux offers the RTM_GETNSID request that maps a network namespace identified either by fd (NETNSA_FD) or by PID (NETNSA_PID) to the local netnsid.
How do I make such a RTM_GETNSID request in Python, preferably using the pyroute2 library? So far, I could not successfully request the netnsid for the namespace identified by PID, but only get back an invalid argument error 22, using the following script:
from pyroute2 import IPRoute
from pyroute2.netlink import NLM_F_REQUEST
import pyroute2.netlink.rtnl as rtnl
import pyroute2.netlink.rtnl.nsidmsg as nsidmsg
netstack = IPRoute()
req = nsidmsg.nsidmsg()
req['rtgen_family'] = 0
# 12345 is PID of a process inside another network namespace
req['attrs'] = [('NETNSA_PID', 12345)]
ret = netstack.nlm_request(req, rtnl.RTM_GETNSID, NLM_F_REQUEST)
It turns out that my code actually is correct, but there's a bug in pyroute2 causing the RTNETLINK message to be a few octets too short (visible in strace). As a temporary hack around this library bug it is sufficient to set two attributes, so that the kernel accepts the RTNETLINK packet and works on it, even if it isn't fully correct.
from pyroute2 import IPRoute
from pyroute2.netlink import NLM_F_REQUEST
import pyroute2.netlink.rtnl as rtnl
import pyroute2.netlink.rtnl.nsidmsg as nsidmsg
netstack = IPRoute()
req = nsidmsg.nsidmsg()
req['rtgen_family'] = 0
# 12345 is PID of a process inside another network namespace
req['attrs'] = [('NETNSA_PID', 12345), ('NETNSA_PID', 0] # hack around pyroute 0.5.0 bug
ret = netstack.nlm_request(req, rtnl.RTM_GETNSID, NLM_F_REQUEST)

How do I pass my subscription key without putting it through terminal?

So on the python sdk for speaker recognition using Microsoft cognitive on the CreateProfile.py I set my subscription key under the variable subscritionKey (note: the value set to the variable on this example isn't my actual product key) But when I place it into the one of the parameters for the function create_profile I get the error...
Exception: Error creating profile: {"error":{"code":"Unspecified","message":"Access denied due to invalid subscription key. Make sure you are subscribed to an API you are trying to call and provide the right key."}}
Is there I can pass my subscritionKey without having to input it constantly through terminal each time?
import IdentificationServiceHttpClientHelper
import sys
subscritionKey = "j23h4i32h4iu3324iu234h233b43"
def create_profile(subscription_key, locale):
"""Creates a profile on the server.
Arguments:
subscription_key -- the subscription key string
locale -- the locale string
"""
helper = IdentificationServiceHttpClientHelper.IdentificationServiceHttpClientHelper(
subscription_key)
creation_response = helper.create_profile(locale)
print('Profile ID = {0}'.format(creation_response.get_profile_id()))
if __name__ == "__main__":
if len(sys.argv) < 2:
print('Usage: python CreateProfile.py <subscription_key>')
print('\t<subscription_key> is the subscription key for the service')
#sys.exit('Error: Incorrect Usage.')
create_profile(subscritionKey, 'en-us')
My guess is that I'm getting issues because I'm passing it as a string :/
Your question is basically how to consume the SDK, right?
The following code works for me: In a file called main.py that is one level out of the folder Identification:
import sys
sys.path.append('./Identification')
from CreateProfile import create_profile
subscriptionKey = "<YOUR-KEY>"
create_profile(subscriptionKey, "en-us")
Running python main.py (with Python 3), that code returns
Profile ID = cf04bf79-xxxx-xxxxx-xxxx

Python TypeError: execv() arg 2 must contain only strings

I have a below code written to get the Speed of the current running interface on the Linux but when i'm running this script its just throwing the error : TypeError: execv() arg 2 must contain only strings .
would appreciate any help or ideas.
Below is the script:
In the Below script i have 2 functions created
1) The one is get_Inf() which gives the Interface information.
2) The Second One is get_intSpeed() which takes the interface name from the First functon and pass it the os command ethtool which further parsed in via a regex to Fetch only the Speed like 1000Mb/s.
#!/grid/common/pkgs/python/v2.7.10/bin/python
import subprocess
import netifaces
import re
''' This snippet is just to get the Speed of the running interface on the System '''
def get_Inf():
Current_inf = netifaces.gateways()['default'][netifaces.AF_INET][1]
return get_Inf
def get_intSpeed():
spd = subprocess.Popen(['/sbin/ethtool', get_Inf()], stdout=subprocess.PIPE).communicate()[0]
pat_match=re.search(".*Speed:\s+(\d+Mb/s)\s+.*", spd) # "d" means any number of digit following the "Mb/s".
speed = pat_match.group(1)
return speed
def main():
print get_intSpeed()
main()
Below is the os command /sbin/ethtool which has the Speed
information of the Interface along with Other Information.
[root#tss /]# /sbin/ethtool eth0| grep Speed
Speed: 1000Mb/s
[root#tss /]# ethtool eth0
Settings for eth0:
Supported ports: [ TP ]
Supported link modes: 10baseT/Half 10baseT/Full
100baseT/Half 100baseT/Full
1000baseT/Full
Supported pause frame use: No
Supports auto-negotiation: Yes
Advertised link modes: 10baseT/Half 10baseT/Full
100baseT/Half 100baseT/Full
1000baseT/Full
Advertised pause frame use: No
Advertised auto-negotiation: Yes
Speed: 1000Mb/s
Duplex: Full
Port: Twisted Pair
PHYAD: 1
Transceiver: internal
Auto-negotiation: on
MDI-X: Unknown
Supports Wake-on: g
Wake-on: g
Link detected: yes
I am using python version 2.7.10.
Your get_Inf() function will return itself with the return get_Inf statement, which is not a string, that is why execv (which is called by subprocess.Popen) is complaining. You should return Current_Inf from your function.

How to check whether screen is off in Mac/Python?

How do I check whether the screen is off due to the Energy Saver settings in System Preferences under Mac/Python?
Quick and dirty solution: call ioreg and parse the output.
import subprocess
import re
POWER_MGMT_RE = re.compile(r'IOPowerManagement.*{(.*)}')
def display_status():
output = subprocess.check_output(
'ioreg -w 0 -c IODisplayWrangler -r IODisplayWrangler'.split())
status = POWER_MGMT_RE.search(output).group(1)
return dict((k[1:-1], v) for (k, v) in (x.split('=') for x in
status.split(',')))
In my computer, the value for CurrentPowerState is 4 when the screen is on and 1 when the screen is off.
Better solution: use ctypes to get that information directly from IOKit.
The only way i can think off is by using OSX pmset Power Management CML Tool
DESCRIPTION
pmset changes and reads power management settings such as idle sleep timing, wake on administrative
access, automatic restart on power loss, etc.
Refer to the following link, it will provide a great deal of information that should aid you in accomplishing exactly what you are looking for.
http://managingamac.blogspot.com/2012/12/power-assertions-in-python.html
I will include the code provided by the link for "saving and documentation" purposes:
#!/usr/bin/python
import ctypes
import CoreFoundation
import objc
import subprocess
import time
def SetUpIOFramework():
# load the IOKit library
framework = ctypes.cdll.LoadLibrary(
'/System/Library/Frameworks/IOKit.framework/IOKit')
# declare parameters as described in IOPMLib.h
framework.IOPMAssertionCreateWithName.argtypes = [
ctypes.c_void_p, # CFStringRef
ctypes.c_uint32, # IOPMAssertionLevel
ctypes.c_void_p, # CFStringRef
ctypes.POINTER(ctypes.c_uint32)] # IOPMAssertionID
framework.IOPMAssertionRelease.argtypes = [
ctypes.c_uint32] # IOPMAssertionID
return framework
def StringToCFString(string):
# we'll need to convert our strings before use
return objc.pyobjc_id(
CoreFoundation.CFStringCreateWithCString(
None, string,
CoreFoundation.kCFStringEncodingASCII).nsstring())
def AssertionCreateWithName(framework, a_type,
a_level, a_reason):
# this method will create an assertion using the IOKit library
# several parameters
a_id = ctypes.c_uint32(0)
a_type = StringToCFString(a_type)
a_reason = StringToCFString(a_reason)
a_error = framework.IOPMAssertionCreateWithName(
a_type, a_level, a_reason, ctypes.byref(a_id))
# we get back a 0 or stderr, along with a unique c_uint
# representing the assertion ID so we can release it later
return a_error, a_id
def AssertionRelease(framework, assertion_id):
# releasing the assertion is easy, and also returns a 0 on
# success, or stderr otherwise
return framework.IOPMAssertionRelease(assertion_id)
def main():
# let's create a no idle assertion for 30 seconds
no_idle = 'NoIdleSleepAssertion'
reason = 'Test of Pythonic power assertions'
# first, we'll need the IOKit framework
framework = SetUpIOFramework()
# next, create the assertion and save the ID!
ret, a_id = AssertionCreateWithName(framework, no_idle, 255, reason)
print '\n\nCreating power assertion: status %s, id %s\n\n' % (ret, a_id)
# subprocess a call to pmset to verify the assertion worked
subprocess.call(['pmset', '-g', 'assertions'])
time.sleep(5)
# finally, release the assertion of the ID we saved earlier
AssertionRelease(framework, a_id)
print '\n\nReleasing power assertion: id %s\n\n' % a_id
# verify the assertion has been removed
subprocess.call(['pmset', '-g', 'assertions'])
if __name__ == '__main__':
main()
https://opensource.apple.com/source/PowerManagement/PowerManagement-211/pmset/pmset.c
The code relies on IOPMLib, which functions to make assertions, schedule power events, measure thermals, and more.
https://developer.apple.com/documentation/iokit/iopmlib_h
To call these functions through Python, we must go through the IOKit Framework.
https://developer.apple.com/library/archive/documentation/DeviceDrivers/Conceptual/IOKitFundamentals/Introduction/Introduction.html
In order for us to manipulate C data types in Python, we'll use a foreign function interface called ctypes.
http://python.net/crew/theller/ctypes/
Here's the wrapper the author describe's on the page; written by Michael Lynn. The code i posted from the Author's link above is a rewrite of this code to make it more understandable.
https://github.com/pudquick/pypmset/blob/master/pypmset.py

Categories

Resources