Calling Python code from Gnome Shell extension - python

I was looking for some time, but still can't find any documented way to call python functions from GnomeShell extension code. Is there any possibility to do that?

You can do it like this :)
const Util = imports.misc.util;
let python_script = '/path/to/python/script';
Util.spawnCommandLine("python " + python_script);

I don't know how to directly call a python function from Gnomeshell, but there is an alternative way. As gnomeshell is programmed with Javascript you could use a python to javascript compiler to translate the python functions you need.

Related

How to clear a terminal in pyscript (py-terminal)

The idea is to clear the output of the python REPL provided by pyscript, embedded in a website.
I have tried the regular ways used in the OS console (os.system("clear"), print("\033c") and similar), but they don't work.
I have not found anything in the documentation of the py-repl or py-terminal elements.
A possible approach is to implement a function in python that uses the js module provided by pyscript to modify the DOM (see How to perform DOM manipulation using pyscript).
So a simplified version of my solution would look like this:
<py-script>
from js import document as _DOC
def clear():
ter = _DOC.getElementById("my-terminal")
ter.innerHTML = ''
</py-script>
Put this code before your REPL and now you can execute the clear() function from it and the terminal will be cleared.

How to achieve "neat" line breaking for several arguments in Python + VSCode?

I am new to Python and I couldn't find the answer for this precise question elsewhere. Let's say one is using a Python function with several inputs. Ideally, for readability, I would like to write code as
my_variable = my_function (arg1 = bla_bla_bla_1,
arg2 = bla_bla_bla_2,
arg3 = bla_bla_bla_3)
This is very easy on RStudio with, for example, just using Enter. I am using Python on Visual Studio Code but I can't find a way to do it. Ideally, it would look like this:
But of course such code won't run since Enter and Tab or Space will break it. Is there anyway to achieve this? I see that this is different than, let's say, code wrapping. But I don't know the name of this property/way of writing code. Thanks in advance!
Using \ should do the trick like so:
a = [5,4,6,\
4,5,6]
Python is quite prescriptive about style. The spec is known as PEP-8 https://www.python.org/dev/peps/pep-0008/
You can install a “linter” in VSCode which will alert you to general style breaches. See https://code.visualstudio.com/docs/python/linting
For your specific question, I think this is the prescribed way.
variable = my_function(
arg1 = bla_bla_bla_1,
arg2 = bla_bla_bla_2,
arg3 = bla_bla_bla_3,
)
You might disagree, but python doesn’t leave much room for your opinion on this 😀. This can be frustrating at first, but when embraced allows you to focus on coding instead of style; and, crucially, a standard style ensures readability when code is shared by multiple python developers.

Calling python functions without running from the editor

Please excuse what I know is an incredibly basic question that I have nevertheless been unable to resolve on my own.
I'm trying to switch over my data analysis from Matlab to Python, and I'm struggling with something very basic: in Matlab, I write a function in the editor, and to use that function I simply call it from the command line, or within other functions. The function that I compose in the matlab editor is given a name at the function definition line, and it's generally best for the function name to match the .m file name to avoid confusion.
I don't understand how functions differ in Python, because I have not been successful translating the same approach there.
For instance, if I write a function in the Python editor (I'm using Python 2.7 and Spyder), simply saving the .py file and calling it by its name from the Python terminal does not work. I get a "function not defined" error. However, if I execute the function within Spyder's editor (using the "run file" button), not only does the code execute properly, from that point on the function is also call-able directly from the terminal.
So...what am I doing wrong? I fully appreciate that using Python isn't going to be identical to Matlab in every way, but it seems that what I'm trying to do isn't unreasonable. I simply want to be able to write functions and call them from the python command line, without having to run each and every one through the editor first. I'm sure my mistake here must be very simple, yet doing quite a lot of reading online hasn't led me to an answer.
Thanks for any information!
If you want to use functions defined in a particular file in Python you need to "import" that file first. This is similar to running the code in that file. Matlab doesn't require you to do this because it searches for files with a matching name and automagically reads in the code for you.
For example,
myFunction.py is a file containing
def myAdd(a, b):
return a + b
In order to access this function from the Python command line or another file I would type
from myFunction import myAdd
And then during this session I can type
myAdd(1, 2)
There are a couple of ways of using import, see here.
You need to a check for __main__ to your python script
def myFunction():
pass
if __name__ == "__main__":
myFunction()
then you can run your script from terminal like this
python myscript.py
Also if your function is in another file you need to import it
from myFunctions import myFunction
myFunction()
Python doesn't have MATLAB's "one function per file" limitation. You can have as many functions as you want in a given file, and all of them can be accessed from the command line or from other functions.
Python also doesn't follow MATLAB's practice of always automatically making every function it can find usable all the time, which tends to lead to function name collisions (two functions with the same name).
Instead, Python uses the concept of a "module". A module is just a file (your .py file). That file can have zero or more functions, zero or more variables, and zero or more classes. When you want to use something from that file, you just import it.
So say you have a file 'mystuff.py':
X = 1
Y = 2
def myfunc1(a, b):
do_something
def myfunc2(c, d):
do_something
And you want to use it, you can just type import mystuff. You can then access any of the variables or functions in mystuff. To call myfunc2, you can just do mystuff.myfunc2(z, w).
What basically happens is that when you type import mystuff, it just executes the code in the file, and makes all the variables that result available from mystuff.<varname>, where <varname> is the name of the variable. Unlike in MATLAB, Python functions are treated like any other variable, so they can be accessed just like any other variable. The same is true with classes.
There are other ways to import, too, such as from mystuff import myfunc.
You run python programs by running them with
python program.py

Python C API - Reload a module

I use Python 3.4 and Visual 2010.
I'm embedding Python using the C API to give the user some script capabilities in processing his data. I call python functions defined by the user from my C++ code. I call specific function like Apply() for example that the user has to define in a Python file.
Suppose the user has a file test.py where he has defined a function Apply() that process some data.
All I have to do is to import his module and get a "pointer" to his python function from the C++.
PySys_SetPath(file_info.absolutePath().toUtf8().data()));
m_module = PyImport_ImportModule(module_name.toUtf8().data());
if (m_module)
{
m_apply_function = PyObject_GetAttrString(m_module, "Apply");
m_main_dict = PyModule_GetDict(m_module);
}
So far, so good. But if the user modifies his script, the new version of his function is never taken into account. I have to reboot my program to make it work... I read somewhere that I need to reload the module and get new pointers on functions but the PyImport_ReloadModule returns NULL with "Import error".
// .... code ....
// Reload the module
m_module = PyImport_ReloadModule(m_module);
Any ideas ?
Best regards,
Poukill
The answer was found in the comments of my first post (thank you J.F Sebastian), the PySys_SetPath has to contain also the PYTHONPATH. In my case, that is the reason why the PyImport_ReloadModule was failing.
QString sys_path = file_info.absolutePath() + ";" + "C:\\Python34\\Lib";
PySys_SetPath(UTF8ToWide(sys_path.toUtf8().data()));
m_module = PyImport_ReloadModule(m_module); // Ok !

How to Pass variables to python script?

I know it can be achieved by command line but I need to pass at least 10 variables and command line will mean too much of programming since these variables may or may not be passed.
Actually I have build A application half in vB( for GUI ) and Half in python( for script ). I need to pass variables to python, similar, to its keywords arguments, i.e, x = val1, y = val2. Is there any way to achieve this?
If you are using Python <2.7 I would suggest optparse.
optparse is deprecated though, and in 2.7 you should use argparse
It makes passing named parameters a breeze.
you can do something fun like call it as
thepyscript.py "x = 12,y = 'hello world', z = 'jam'"
and inside your script,
parse do:
stuff = arg[1].split(',')
for item in stuff:
exec(item) #or eval(item) depending on how complex you get
#Exec can be a lot of fun :) In fact with this approach you could potentially
#send functions to your script.
#If this is more than you need, then i'd stick w/ arg/optparse
Since you're working on windows with VB, it's worth mentioning that IronPython might be one option. Since both VB and IronPython can interact through .NET, you could wrap up your script in an assembly and expose a function which you call with the required arguments.
Have you taken a look at the getopt module? It's designed to make working with command line options easier. See also the examples at Dive Into Python.
If you are working with Python 2.7 (and not lower), than you can also have a look at the argparse module which should make it even easier.
If your script is not called too often, you can use a configuration file.
The .ini style is easily readable by ConfigParser:
[Section_1]
foo1=1
foo2=2
foo3=5
...
[Section_2]
bar1=1
bar2=2
bar3=3
...
If you have a serious amount of variables, it might be the right way to go.
What do you think about creating a python script setting these variables from the gui side? When starting the python app you just start this script and you have your vars.
Execfile

Categories

Resources