No module named <module> - python

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

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

Failed to copy file from host to ansible server

I'm trying to do a simple process with ansible, however I get failed when trying to run this playbook, I would just like to take the existing file in the user's temporary directory and copy it back to the ansible server inside etc/ansible/files
path and permissions
root#ansible:/etc/ansible/files# pwd
/etc/ansible/files
root#ansible:/etc/ansible/files# ls -ltr ../
total 24
-rw-r--r-- 1 root root 535 mar 27 11:23 ansible.cfg
-rw-r--r-- 1 root root 188 mar 27 15:41 hosts
drwxr-xr-x 5 root root 4096 mar 27 15:42 roles
drwxr-xr-x 2 root root 4096 mar 27 15:42 group_vars
drwxrwxrwx 2 root root 4096 mar 27 16:59 files
drwxr-xr-x 3 root root 4096 mar 27 17:01 playbook
playbook
- name: auto_collect_pingprobe
hosts: "{{ affected_host }}"
gather_facts: no
tasks:
- block:
- name: 'Copy net connect'
fetch:
src: '%temp%\net_connect.cfg'
dest: '/etc/ansible/files/net_connect.cfg'
flat: yes
rescue:
- fail:
msg: "Failure detected in playbook"
output
fatal: [192.168.238.12]: FAILED! => {
"msg": "failed to transfer file to \"/etc/ansible/files/net_connect.cfg\""
}
TASK [fail] *************************************************************************************************************************************************
task path: /etc/ansible/playbook/GEN_AUTO_COLLECT_HOST_AVAILABLE.yml:22
fatal: [192.168.238.12]: FAILED! => {
"changed": false,
"msg": "Failure detected in playbook"
}
Two things may be going on.
You may not have root permissions on the controlled node, ensure that you are using the --become flag when invoking the notebook (or use equivalent privilege escalation).
The %temp% variable may not be being read from the environment. Try replacing the src string with '{{ lookup("env", "temp") }}\net_connect.cfg'.

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

Raspberry Pi (Raspbian Linux flavor) run script on wifi up

Currently I am experience issues with the script automatic run after wifi adapter connects to a network.
After ridiculously extended research, I've made several attempts to add script to a /etc/network/if-up.d/. Manually my script works; however it does not automatically.
User permissions:
ls -al /etc/network/if-up.d/*
-rwxr-xr-x 1 root root 703 Jul 25 2011 /etc/network/if-up.d/000resolvconf
-rwxr-xr-x 1 root root 484 Apr 13 2015 /etc/network/if-up.d/avahi-daemon
-rwxr-xr-x 1 root root 4958 Apr 6 2015 /etc/network/if-up.d/mountnfs
-rwxr-xr-x 1 root root 945 Apr 14 2016 /etc/network/if-up.d/openssh-server
-rwxr-xr-x 1 root root 48 Apr 26 03:21 /etc/network/if-up.d/sendemail
-rwxr-xr-x 1 root root 1483 Jan 6 2013 /etc/network/if-up.d/upstart
lrwxrwxrwx 1 root root 32 Sep 17 2016 /etc/network/if-up.d/wpasupplicant -> ../../wpa_supplicant/ifupdown.sh
Also, I've tried to push the command directly in /etc/network/interfaces
by adding a row
post-up /home/pi/r/sendemail.sh
Contents of sendemail.sh:
#!/bin/sh
python /home/pi/r/pip.py
After the reboot, nothing actually happen. I've even tried sudo in front
I assume that wpasupplicant is the thing which causes that, but I cannot get how to run my script in ifupdown.sh script under /etc/wpa_supplicant.
Appreciate your help!
If you have no connectivity prior to initializing the wifi interface, I would suggest adding a cron job of a bash or python script that checks for connectivity every X minutes.
Ping (host);
If host is up then run python commands or external command.
This is rather ambiguous but hopefully is of some help.
Here is an example of a script that will check if a host is alive;
import re,commands
class CheckAlive:
def __init__(self):
myCommand = commands.getstatusoutput('ping ' + 'google.com)
searchString = r'ping: unknown host'
match = re.search(searchString,str(myCommand))
if match:
# host is not alive
print 'no alive, don't do stuff';
else:
# host is alive
print 'alive, time do stuff';

ImportError: No module named mymodule.main

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

Categories