Problems with importing a python library - python

Currently I'm trying to use this python library:
https://github.com/etotheipi/BitcoinArmory/blob/master/armoryd.py
Essentially, I'm able to run:
python armoryd armory_2BEfTgvpofds_.watchonly.wallet
Only when I pass a .wallet argument.
I want to do the same with a script that I create. But when I import the library, it's asking for a wallet argument. When I do something like:
import armoryd armory_2BEfTgvpofds_.watchonly.wallet
It is complaining about an invalid syntax.
Is it possible to import this library?

from armoryd import armory_2BEfTgvpofds_.watchonly.wallet
Your import statement is invalid, it needs to be from MODULE import SOMETHING1, SOMETHING2...etc
Also you need to ensure that your armoryd library is on the PYTHONPATH
update
https://github.com/etotheipi/BitcoinArmory/blob/master/extras/sample_armory_code.py
take a look there - a sample on how to use the armory code in python.

Looking at the source code for this library, you won't be able to import it in such a way. It is hard coded to take parameters from the command line.
if len(CLI_ARGS)==0:
LOGERROR('Please supply the wallet for this server to serve')
LOGERROR('USAGE: %s [--testnet] [--whatever] file.wallet' % sys.argv[0])
os._exit(1)
As Mike McMahon mentioned, there is a way to import the code, but you won't be able to import armoryd.
https://github.com/etotheipi/BitcoinArmory/blob/master/extras/sample_armory_code.py

Related

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.

How to check a Python script's the correct version automatically while the shebang is not accurate?

For example, I find download_model_binary.py's shebang is wrong while it contains a Python 2 library function urllib.urlretrieve.
I try to use two python interpreters to execute the file and watch its return value in script, but it will lead side effect.
Note: I am asking how detect the correct version of a existing Python 2 script like download_model_binary.py which has the wrong shebang, not how to rewrite it to be compatible.
You could do something like this:
import sys
if sys.version_info.major < 3:
from urllib import urlretrieve
else:
from urllib.request import urlretrieve
And later use:
urlretrieve(frontmatter['caffemodel_url'], model_filename, reporthook)
If you need this often consider using Python Future. It offers a good solution for this type of problem.

Is there an accepted way in Python to import a module from within a function?

I have written a script for XBMC which optionally downloads a dll and then imports a module that depends on that dll if the download was successful.
However, placing the import inside a function generates a Python syntax warning.
Simplified example:
1 def importIfPresent():
2 if chkFunction() is True:
3 from myOptionModule import *
Line 3 generates the warning, but doesn't stop the script. I can't place this code at the start outside of a function because I need to generate dialog boxes to prompt the download and then hash the file once it is downloaded to check success. I also call this same code at startup in order to check if the user has already downloaded the dll.
Is there a different/better way to do this without generating the syntax warning? Or should I just ignore the warning and leave it as is?
Thank you! Using the useful responses below, I now have:
import importlib
myOptionalModule = None
def importIfPresent():
if chkFunction is True:
try:
myOptionalModule = importlib.import_module('modulex')
except ImportError:
myOptionalModule = None
...
importIfPresent()
...
def laterFunction():
if myOptionalModule != None:
myParam = 'something expected'
myClass = getattr(myOptionalModule, 'importClassName')
myFunction = getattr(myClass, 'functionName')
result = myFunction(myClass(), myParam)
else:
callAlternativeMethod()
I am posting this back mainly to share with other beginners like myself the way I learned through the discussion to use the functionality of a module imported this way instead of the standard import statement. I'm sure that there are more elegant ways of doing this that the experts will share as well...
You're not getting the warning for doing an import inside a function, you're getting the warning for using from <module> import * inside a function. Doing a In Python3, this actually becomes a SyntaxError, not a SyntaxWarning. See this answer for why wildcard imports like this in general, and expecially inside functions are discouraged.
Also, this code isn't doing what you think it does. When you do an import inside a function, the import only takes affect inside the function. You're not importing that module into the global namespace of the file, which I believe is what you're really trying to do.
As suggested in another answer importlib can help you here:
try:
import myOptionModule as opt
except ImportError:
opt = None
def importIfPresent():
global opt
if chkFunction() is True:
opt = importlib.import_module("myOptionModule")
I beleive you need to use the importlib library to facilitate this.
The code would be at the top of the mod:
import importlib
then replace "from myOptionModule import *" with "module = importlib.import_module(myOptionModule)". You can then import the defs/classes you want or import them all by using getattr(module,NAME(S)TOIMPORT).
See if that works.
Check out chapter 30 and 31 of Learning Python by Lutz for more info.

ImportError for jsonrpc

I am trying to follow this walkthrough on how to use the ServiceProxy in jsonrpc.
I followed the directions but I am getting an error no the import of the ServiceProxy.
Here is the code I am using:
#!usr/bin/python
import sys
import json
from jsonrpc import ServiceProxy
givex = jsonrpc.ServiceProxy()
print "foo"
which is resulting in:
Would anyone be able to help me out with some ideas on how to fix this, or have a suggestion for a better jsonrpc library to use.
The tutoral you are following seems to be outdated. Try
from jsonrpc.proxy import JSONRPCProxy
givex = JSONRPCProxy.from_url("http://localhost/url/of/your/service.py")
If you are trying to run this under Python 3.x, bear in mind that it is not yet supported. Many JSON RPC libraries have very similar names, but this particular one (jsonrpc without the dash, different from json-rpc or jsonrpc2) does not support Python 3 as of december 2016.
Here is the link for this particular library: https://pypi.python.org/pypi/jsonrpc

Accessing a function from a module

I cant figure out how to add my simple function to my main program file. why not ?
when i do this:
import print_text
echothis("this is text")
exit()
cant understand why people think this is such a bad question.
this doesnt work either:
print_text.echothis("this is text")
same thing happens if i type any of the answers below.
including:
from print_text import echothis
I just get this error:
from: can't read /var/mail/print_text
./blah3.py: line 3: syntax error near unexpected token `"this is text"'
./blah3.py: line 3: `print_text.echothis("this is text")'
or a variant without the /var/mail line...
*this file is named print_text.py*
#!/usr/bin/env python
import time
import random
import string
import threading
import sys
def echothis(txt):
woo=txt
stdout.write(woo)
EDIT: You're actually not having a python issue but a bash one. You're running your python script as if it were bash (hence the 'from: can't read from'), did you put #!/usr/bin/env python at the beginning of the file you're running (not print_text.py, the other one)? You could alternatively call it that way: python myfile.py and it should work.
When you import a module, it is namespaced, so if you want to use anything that is from that module, you need to call it using the proper namespace. Here, you would call you echothis function using print_text.echothis.
Alternatively, if you want to include echothis in your main namespace, you can use the from print_text import echothis syntax.
Try this:
import print_text
print_text.echothis("this is a text")

Categories

Resources