Sagemath as daemon service - name 'e' is not defined" - python

I have been using Sagemath as a daemon service following the Python code presented here:
https://ask.sagemath.org/question/23431/running-sage-from-other-languages-with-higher-performance/
That code sets up Sagemath as a daemon service using python sockets
I make sockets calls via php sockets to connect with this sagemath daemon, and it works fine, except that it does not recognize the constant 'e', while it does recognize 'pi'.
For example, if I run simplify(4*pi^2*pi^3) through the socket call, it will do the algebra correctly, whereas if I run simplify(4*pi^2*pi^3*e), it returns the error:
ERROR: <class 'NameError'> name 'e' is not defined
From what I have gathered, when run this way Sagemath will need to import libraries explicitly. The imports in the python daemon are:
import sys
from io import StringIO
from sage.all import *
from sage.calculus.predefined import x
from sage.repl.preparse import preparse

A temporary workaround is using exp(1) for the e.

Related

Python: Django: How to run django app using a python script

I've a python file named "config.py" which actually checks the ip of user and run the django server on that port accordingly. The method I used there was to create a batch file using python and execute it later.
import socket
import subprocess
x = socket.gethostbyname(socket.gethostname())
x = str(x)
with open("run.bat", "w") as f:
f.write(f'manage.py runserver {x}:0027')
subprocess.call([r'run.bat'])
But this method is not very effective. I want a way like:
import something
something.run("manage.py")
or something accordingly
Kindly Help me doing this
Edit:
I've seen Django's manage.py.
Can I edit this file (the sys.argv section) in such a way that it automatically runs a server on 192.168.x.x:8000 just by clicking on manage.py?
Please help
I think the method you're trying to reach is to run a shell command inside a python script, which can be achieved by using the os.system() function.
You can use it in your code as the following:
import socket
import subprocess
import os
x = socket.gethostbyname(socket.gethostname())
x = str(x)
os.system(f'manage.py runserver {x}:0027')

How can I fix SyntaxError: invalid syntax/ import * from modbus?

I want to get the .exe file from a code source but doing python main.py build results in this error:
C:\MyProject>python main.py build
Traceback (most recent call last):
File "main.py", line 5, in <module>
import parserz as parser
File "C:\MyProject\parserz.py", line 9
import * from modbus
^
SyntaxError: invalid syntax
Any idea please?
Maybe a problem with pip?
In python you import like this
from modbus import *
Also, In python its good practice to import only what you need.
So you shouldn't use from .... import * instead use
from modbus import something
You can either import the module and run all normal code with
import modbus
or you can import all the classes, functions, variables, etc., from the file to use later in your code with
from modbus import *
To illustrate my point:
If you have two files my_imports.py and main.py that contain the following code:
my_imports.py:
print('Imported module my_imports')
def add_nums(a,b):
return a+b
def another_function():
return 'this function was also called'
(version 1) main.py:
import my_imports
# this code would fail because the function isn't imported
print(add_nums(5,7))
(version 2) main.py:
from my_imports import *
print(add_nums(5,7))
print(another_function())
In verion 1 of main.py you would see Imported module my_imports in the output but your code would fail when you try to use the
add_nums function defined in my_imports.py.
In version 2 of main.py you would still see Imported module my_imports in the output but you would also see the result of calling the other two functions in the output as they are now available for use in main.py:
12
this function was also called
As mentioned in some of the other answers, you can also just import the functionality you want from another python script. For example, if you only wanted to use the add_nums method, you could instead have
from my_imports import add_nums
in your main.py.
Generally from modbus import * should be enough. But it is generally not a good idea to import all so I recommend import modbus as mb. Also you might want to look into modbus libraries like pyModbus or minimalModbus. Here's a good link depicting their pros and cons: Python modbus library

Cannot import Python function in Jython

I wrote a Python script which is executed via Jython 2.7. I need SQLite, so I decided to use sqlite3 for Jython (link) which is under /usr/local/lib/jython/Lib.
ghidra_batch.py
import sys
sys.path.append("/usr/local/lib/jython/Lib")
sys.path.append("/path/to/my/project/directory")
import sqlite3
I created another file where I define some functions for my database:
db.py
import platform
import sys
if platform.python_implementation == 'Jython':
sys.path.append("/usr/local/lib/jython/Lib")
sys.path.append("/path/to/my/project/directory")
import sqlite3
def open_db():
[some code]
def create_schema():
[some code]
Note: I check Python implementation because this script is run also via CPython. I append the path only when run via Jython to make it find its sqlite3 module, in case of CPython standard sqlite3 module is used.
Now my problem happens when I import open_db() in ghidra_batch.py:
from db import open_db
The result is the following:
ImportError: cannot import name open_db
Thanks for your help.
As a general rule: when working with Python, when something isn't not what you're expecting, simply print it.
Your from db import open_db line which was triggering that exception "told" me that:
The db module (package) was found
It's not the one that you're expecting to be (your db.py)
That's why I suggested in my comment to print information about it (obviously, before the error is hit):
import db
print(db)
print(dir(db))
The output confirmed it. So, there is another db module which is imported before yours. I tried replicating your environment (installed Jython, but I wasn't able to install jython-sqlite3).
After a bit of research, I think it's [BitBucket]: Taro L. Saito/sqlite-jdbc/Source - sqlite-jdbc/src/main/java/org/sqlite/DB.java (sqlite-jdbc is a jython-sqlite3 dependency).
The reasonable way is to modify your module name to something else (e.g.: sqlite_db_wrapper.py), and also update the import statement(s).
As a(n other) general rule, don't give your modules (common) names that might conflict with modules from Python's library.

Programmatically import a module and also use `as` to give it a name

Is there an import utility, such as importlib, that allows programmatically importing a module with a qualified name, such as import numpy as np?
It seems that the plain importlib.import_module() and the imp.load_module functions do not offer this. And the Python docs page on import tools didn't reveal anything either.
Specifically, instead of just doing importlib.import_module("numpy") I'm looking for something that "just works" along the lines of importlib.import_module("numpy", as="np") making the name "np" now available as the imported module.
My use case:
I'm using the DirectView.sync_imports function from IPython.parallel to ensure that all compute engines have the needed modules imported on them locally. This way, a user can execute code in a controller IPython session, but the backend can execute it in parallel.
In this use case, since the code is often just interactive, exploratory scripting, it is important to match exactly whatever import statements and names are provided by the programmer.
So if the following is a function that the programmer would like to map to other engines and execute in parallel on a variety of arguments, the same qualified import would need to be available on all engines:
def my_func(x):
import numpy as np
return np.random.randint(x, size=(10,1))
To get 4 such results, in parallel, a user could do the following (assuming everything with ipcluster or ipcontroller / ipengines is configured and running):
from IPython.parallel import Client
rc = Client()
direct_view = rc[:]
# In parallel.
four_random_arrays = direct_view.map(my_func, [2, 3, 4, 5]).get()
IPython provides a nice context manager for syncing the imports:
# This works fine and syncs the import on all engines.
with direct_view.sync_imports():
import numpy as np
But suppose you only have access to a string: "numpy as np" and you want to use importlib to do this within that context manager block without trying to parse the strings manually and tinker with whatever entries are in the loaded modules dict.
It's probably needless to say, but using exec here is also completely untenable, because what if instead of a module string, someone accidentally passes in something nasty or insecure, like a shell call to rm -rf /. Leveraging import tools that don't allow for execution of arbitrary code is important -- making it untenable to roll one's own string-parsing exec sort of solution.
import_module returns a value (the module being imported) -- set whatever variable you want to the return value of that. For example:
import importlib
p = importlib.import_module('os.path')
p.join('/', 'blah')
would effectively be equivalent to
import os.path as p
p.join('/', 'blah')

WLST scripting and importing self-made module

I am trying to write a WLST script.
As I found that I always repeat doing similar setup, I tried to make some util functions to ease my script writing.
Later when I tried to pull those functions to an external .py as a module, I failed to do so:
assume I have a main script (domain_config.py), and the util function script (wlst_util.py)
Here is what I put in domain_config.py:
import wlst_util import *
loadProperties('domain.properties')
....
create_jms_conn_factory(....);
First it complains for my delcaration in the wlst_util.py for the method:
create_jms_conn_factory(...., is_xa=False)
it complains "NameError: False".
ok, then I remove the default param, then it complains for those cd() function (provided by WLST).
Then I tried to do "from wl import *" in wlst_util.py, the script failed at loadProperties line (NullPointerException).
I tried to put the import after loadProperties, then the cmo variable in my main script become None...
What is the right way I should do just for pulling those util function to a separate file?..
Thanks

Categories

Resources