ImportError: No module named mymodule.main - python

I have a test which requires instructions on how to run. The goal beyond working is to be noobproof, the instruction manual should consist of one command to run file, one to run the test. My friend said running unittests won't require files being on pythonpath because it checks current directory first, but I get:
import unittest
from ordoro_test.main import OrdoroETLMachine
class ETLMachineTests(unittest.TestCase):
def setUp(self):
self.api_url = 'https://9g9xhayrh5.execute-api.us-west-2.amazonaws.com/test/data'
self.headers = {'accept': 'application/json'}
def test_data_is_returned(self):
print(OrdoroETLMachine.get_email_data())
if __name__ == '__main__':
unittest.main()
cchilders:~/ordoro_test [master]$ python test.py
Traceback (most recent call last):
File "test.py", line 4, in <module>
from ordoro_test.main import OrdoroETLMachine
ImportError: No module named ordoro_test.main
cchilders:~/ordoro_test [master]$ ls -l
total 8
-rw-rw-r-- 1 cchilders cchilders 0 Mar 5 19:15 __init__.py
-rwxr-xr-x 1 cchilders cchilders 3099 Mar 5 20:12 main.py
-rwxr-xr-x 1 cchilders cchilders 441 Mar 5 20:19 test.py
How can I fix and allow imports the simplest way possible? Thank you
I try
from ordoro_test.assignment.main import OrdoroETLMachine
No dice

Adding empty __init__.py file in one level with ordoro_testfolder shall fix your problem.
See Python 2.7, Modules section for more information.

Use explicit relative import from .main import OrdoroETLMachine. intra-package-references

Related

Stop the command when find a string - python

I want to print a command until it finds the main.py file and then stops.
I tried this code but according to logic it is printing the code several times and not line by line until I stop at mine where I find the main.py file.
import subprocess
#store ls -l to variable
get_ls = subprocess.getoutput("ls -l")
#transfom output to string
ls = str(get_ls)
#search for main.py file in ls
for line in ls:
main_py = line.find('main.py')
print(ls)
#if find main.py print stop and exit
if main_py == 'main.py':
print('stop...')
exit()
Output is looping this:
-rw-r--r-- 1 runner runner 9009 Feb 19 19:00 poetry.lock
-rw-r--r-- 1 runner runner 354 Feb 19 19:00 pyproject.toml
-rw-r--r-- 1 runner runner 329 Feb 25 00:10 main.py
-rw-r--r-- 1 runner runner 383 Feb 14 17:57 replit.nix
-rw-r--r-- 1 runner runner 61 Feb 19 18:46 urls.tmp
drwxr-xr-x 1 runner runner 56 Oct 26 20:53 venv
I want this output:
-rw-r--r-- 1 runner runner 9009 Feb 19 19:00 poetry.lock
-rw-r--r-- 1 runner runner 354 Feb 19 19:00 pyproject.toml
-rw-r--r-- 1 runner runner 329 Feb 25 00:10 main.py
###### stops here #######
How to fix this?
The line for line in ls isn't doing what you think it is. Instead of going line by line, it's going through ls character by character. What you want to have is for line in ls.splitlines(). You can then check if main.py is on that line by calling "main.py" in line
import subprocess
#store ls -l to variable
get_ls = subprocess.getoutput("ls -l")
#transfom output to string
ls = str(get_ls)
#search for main.py file in ls
for line in ls.splitlines():
print(line)
#if find main.py print stop and exit
if "main.py" in line:
print('stop...')
exit()
That should be more what you want I think.
You're also printing ls every loop, which you need to change to only print the current line
In my opinion, if you only want to achieve the result and don’t mind changing your logic, this the most elegant, and which is the most "pythonic" one. I like the simplicity of the os.walk() method:
import os
for root, dirs, files in os.walk("."):
for filename in files:
print(filename)
if filename == "main.py":
print("stop")
break

can't from module import function but import module ,then module.function is success

I'm writing a project, and found previous normal function failure. After debug, it was found that there was a problem with from module. I type from utils import pub and execute project, it shows mportError: cannot import name 'pub', but if I type 'import utils' and then utils.pub(), it executes successfully. And my other py file that used the from module import function can be used directly
utils.py
import paho.mqtt.client as mqtt
import paho.mqtt.subscribe as subscribe
def pub(topics, payload, mqtt_host, mqtt_port):
client = mqtt.Client()
client.enable_logger(logger)
client.connect(mqtt_host, mqtt_port, 60)
client.loop_start()
client.publish(topics, payload, 2)
client.loop_stop()
handle.py
from utils import pub
... some code
it shows
Traceback (most recent call last):
File "connect.py", line 7, in <module>
from utils import *
File "utils.py", line 1, in <module>
from handle import app_handle
File "handle.py", line 6, in <module>
from utils import pub
ImportError: cannot import name 'pub'
handle.py
import utils
utils.pub(topic,payload,MQTT_IP,MQTT_PORT)
it runs normal
and other connect.py that used from utils import pub runs normal
Part of the project file structure is as follows
total 64
drwxr-xr-x 4 user user 4096 Sep 4 18:36 ./
drwxr-xr-x 3 user user 4096 Aug 3 17:33 ../
-rwxr-xr-x 1 user user 3514 Sep 5 09:14 collect.py*
-rw------- 1 user user 6646 Sep 5 09:56 connect.py
-rwxr-xr-x 1 user user 2403 Sep 5 09:46 handle.py*
drwxr-xr-x 2 root root 4096 Sep 5 09:46 __pycache__/
-rw-rw-r-- 1 user user 17495 Sep 5 09:15 utils.py
Although import can be used to solve this problem, I would like to know what causes this problem

How to call data/variable from a python module?

I created a python module in which I stored a variable. when I run: help(connections_and_variables.connections_and_variables)
I can see in the "DATA" section the variable (dw_path).
How can I call this in the script that reads the module?
NAME
connections_and_variables.connections_and_variables - Created on Fri Jun 15 10:19:46 2018
FILE
c:\users\USER\documents\data-warehouse\connections_and_variables\connections_and_variables.py
DESCRIPTION
#author: USER
FUNCTIONS
db(name)
db_engine(name)
DATA
dw_path = r'C:\Users\USER\Documents\data-warehouse'
Just like you would access anything else from a module:
import connections_and_variables.connections_and_variables
print(connections_and_variables.connections_and_variables.dw_path)
Or:
from connections_and_variables import connections_and_variables
print(connections_and_variables.dw_path)
Or:
from connections_and_variables.connections_and_variables import dw_path
print(dw_path)

Running Python's doctest on a file named `types.py`

In both Python 2 and 3 I cannot run doctests in a file named types.py, which is part of a package. This is what I get:
$ cat foo/types.py
def x():
"""do something
>>> x()
1
"""
return 1
$ cp foo/types.py foo/types2.py
$ python -m doctest -v foo/types.py
1 items had no tests:
types
0 tests in 1 items.
0 passed and 0 failed.
Test passed.
$ python -m doctest -v foo/types2.py
Trying:
x()
Expecting:
1
ok
1 items had no tests:
types2
1 items passed all tests:
1 tests in types2.x
1 tests in 2 items.
1 passed and 0 failed.
Test passed.
$ python3 -m doctest -v foo/types.py
37 items had no tests:
types
types.DynamicClassAttribute
types.DynamicClassAttribute.__delete__
types.DynamicClassAttribute.__get__
types.DynamicClassAttribute.__init__
types.DynamicClassAttribute.__set__
types.DynamicClassAttribute.deleter
types.DynamicClassAttribute.getter
types.DynamicClassAttribute.setter
types.SimpleNamespace
types.SimpleNamespace.__delattr__
types.SimpleNamespace.__eq__
types.SimpleNamespace.__ge__
types.SimpleNamespace.__getattribute__
types.SimpleNamespace.__gt__
types.SimpleNamespace.__init__
types.SimpleNamespace.__le__
types.SimpleNamespace.__lt__
types.SimpleNamespace.__ne__
types.SimpleNamespace.__reduce__
types.SimpleNamespace.__repr__
types.SimpleNamespace.__setattr__
types._GeneratorWrapper
types._GeneratorWrapper.__init__
types._GeneratorWrapper.__iter__
types._GeneratorWrapper.__next__
types._GeneratorWrapper.close
types._GeneratorWrapper.cr_await
types._GeneratorWrapper.gi_code
types._GeneratorWrapper.gi_frame
types._GeneratorWrapper.gi_running
types._GeneratorWrapper.send
types._GeneratorWrapper.throw
types._calculate_meta
types.coroutine
types.new_class
types.prepare_class
0 tests in 37 items.
0 passed and 0 failed.
Test passed.
$ python3 -m doctest -v foo/types2.py
Trying:
x()
Expecting:
1
ok
1 items had no tests:
types2
1 items passed all tests:
1 tests in types2.x
1 tests in 2 items.
1 passed and 0 failed.
Test passed.
As you see, all invocations with foo/types2.py work as expected, all invocations with foo/types.py seem to try to load the Python built-in types module.
I'm also not able to fix this by tinkering with PYTHONPATH:
$ PYTHONPATH=.:$PYTHONPATH python -m doctest -v foo/types.py
Traceback (most recent call last):
File "/usr/lib/python2.7/site.py", line 68, in <module>
import os
File "/usr/lib/python2.7/os.py", line 400, in <module>
import UserDict
File "/usr/lib/python2.7/UserDict.py", line 116, in <module>
import _abcoll
File "/usr/lib/python2.7/_abcoll.py", line 70, in <module>
Iterable.register(str)
File "/usr/lib/python2.7/abc.py", line 107, in register
if not isinstance(subclass, (type, types.ClassType)):
AttributeError: 'module' object has no attribute 'ClassType'
Unfortunately, I cannot simply rename foo/types.py.
Is there any possibility to run doctests from this file apart from writing lots of boilerplate code around it?
I don’t think you can use python -m doctest here: the documentation says that it “import[s the module] as a standalone module”, adding
Note that this may not work correctly if the file is part of a package and imports other submodules from that package.
which is a fancy way of saying that it uses the module’s unqualified name. Of course it then conflicts with the standard library module.

No module named <module>

I'm really new to Python - I'm trying to do this:
import bottle.run, bottle.route, bottle.template
#bottle.Bottle.route('/hello/<name>')
def index(name):
return template('<b>Hello {{name}}</b>!', name=name)
run(host='localhost', port=8080)
and here is the listing of my current working directory, with my script being bot.py:
-rw-r--r-- 1 ctote gos-eng 196 Oct 1 20:54 bot.py
-rw-r--r-- 1 ctote gos-eng 148901 Oct 1 19:55 bottle.py
-rw-r--r-- 1 ctote gos-eng 167884 Oct 1 20:26 bottle.pyc
-r-xr-xr-x 1 ctote gos-eng 0 Oct 1 20:25 __init__.py
drwxr-xr-x 2 ctote gos-eng 4096 Oct 1 19:55 pip-egg-info
-rw-r--r-- 1 ctote gos-eng 1692 Oct 1 19:55 PKG-INFO
-rw-r--r-- 1 ctote gos-eng 1057 Oct 1 19:55 README.rst
-rw-r--r-- 1 ctote gos-eng 1516 Oct 1 19:55 setup.py
drwxr-xr-x 3 ctote gos-eng 4096 Oct 1 19:55 test
However, I keep getting this error:
python bot.py
Traceback (most recent call last): File "bot.py", line 1, in <module>
import bottle.run, bottle.route, bottle.template ImportError: No module named run
Within bottle.py, there's this:
def run(self, **kwargs):
''' Calls :func:`run` with the same parameters. '''
run(self, **kwargs)
What am I doing wrong? Ideally I'd rather not have my script in this directory, but I figured this was the easiest way to get started..
bottle is a module. bottle.run is an object (a function), contained in that module.
Import just the module:
import bottle
and refer to bottle.run in your code, or import the objects from the module:
from bottle import run, route, template

Categories