I' m happy trouble understanding why the function below seems to be outputting None instead of 1 if the function doesn't have a vakud output on its first run through.
import win32com.client
BING_KEY = "XXXXXXXX"
import speech_recognition as sr
import win32com.client as wincl
s = sr.Recognizer()
def hey_pc():
print(" Hey PC = Command")
with sr.Microphone() as source:
audio = s.listen(source)
try:
x= (s.recognize_bing(audio, key=BING_KEY))
if x in ['hey PC']:
return 1
else: hey_pc()
except:
print('Try again')
hey_pc()
t = hey_pc()
print t
if the function outputs on its first run, I get the following output:
Hey PC == Command
1
But if it invokes its recursive property, I get a final output of None
Hey PC == Command
Hey PC == Command
Hey PC == Command
Hey PC == Command
None
or this
Hey PC == Command
Try again
Hey PC == Command
Hey PC == Command
None
I don't understand why I"m getting "None."
EDIT:
I've changed the second part of the code to this and played around more but still have the same problem:
t =hey_pc()
if t == 1:
speak = wincl.Dispatch("SAPI.SpVoice")
speak.Speak("This is the pc voice speaking")
import automation
automation.Apply_Command()
else:
hey_pc()
If my voice is recognized on its first attempt, the code under if t==1 is ran and there no problems, however if my voice is not recognized on its first attempt and recurvise portion of the code is activated, once my voice finally gets recognized, the program just ends (meaning the Python command prompt >>> pops up again). So I'm assuming it's the null value that's being passed on.
Still stumped. :(
Probably not the answer you're looking for, specifically, but it's generally because "if x in ['hey PC']" is NEVER true. The only condition where a number is returned (and thus setting a value) is your if statement. So, most likely, that if statement is never entered into.
Related
Here is my python code that I am using. I am trying to use a wii remote to trigger a buzzer. I thought this would be an interesting use for my old wii remote. The code that interacts with the buzzer works fine because I used an example script to test it. However, when I try and run it I keep getting this one error (see bottom). I am new to python and would appreciate any help.
import cwiid
from gpiozero import LED
import time
import os
Buzzer1 = LED(17)
Buzzer2 = LED(27)
def ConnectRemote():
os.system("rfkill unblock bluetooth")
print 'Press 1+2 On The Remote...'
global wm
wm = wiid.Wiimote()
print 'Connection Established!\n'
wm.led = 1
wm.rumble = 1
time.sleep(0.25)
wm.rumble = 0
time.sleep(0.5)
wm.rpt_mode = cwiid.RPT_BTN
def TryToConnect():
while True:
ConnectRemote()
break
while True:
buttons = wm.state['buttons']
#shutdown function using plus and minus buttons
if (buttons - cwiid.BTN_PLUS - cwiid.BTN_MINUS == 0):
print '\nClosing Connection To Wiimote'
wm.rumble = 1
time.sleep(0.25)
wm.rumble = 0
os.system("rfkill block bluetooth")
TryToConnect()
if (buttons & cwiid.BTN_A):
print 'Buzzer On'
Buzzer1.on()
Buzzer2.on()
else:
Buzzer1.off()
Buzzer2.off()
and yet I keep getting an error of
Traceback (most recent call last):
File "WiimoteLEDs.py", line 36, in <module>
buttons = wm.state['buttons']
NameError: global name 'wm' is not defined
Can anyone help? Thanks in advance
I think you should initialized variable wm before using this variable in function.
This bug is related to 'Global name not defined'
I work with python 2.7 and I have a python script that ssh to remote servers and it works fine using python command from cmd but when I convert this script to executable file using py2exe or cx_freeze or Pyinstaller and try to run it, the window open and close immediately like if the program crashes. I tried another simple scripts like print function or some math function the executable files work fine so any one could help what would be the reason?
Thanks
Here is my code:
import sys
import paramiko
import getpass
def print_menu():
print 30 * "-", "MENU", 30 * "-"
print "1. LAB1"
print "2. LAB2"
print "3. LAB3"
print "4. Exit"
print 67 * "-"
def ssh_command(ssh):
while True:
command = raw_input("Enter command or q :")
ssh.invoke_shell()
stdin, stdout, stderr = ssh.exec_command(command)
stdout = stdout.readlines()
if command == "q":
break
for line in stdout:
if "Size" in line:
print "found the string"
break`enter code here`
else:
print "There was no output for this command"
def ssh_connect(host, user, password):
try:
ssh = paramiko.SSHClient()
print('Connecting...')
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=host, username=user, password=password)
ssh_command(ssh)
except Exception as e:
print('Connection Failed')
print(e)
def ssh_close():
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.close()
def credentials(host):
user = raw_input("Username:")
password = getpass.getpass("password for " + user + ":")
ssh_connect(host, user, password)
loop = True
while loop:
print_menu()
choice = input("Enter your choice [1-3]: ")
if choice == 1:
credentials('x.x.x.x')
elif choice == 2:
credentials('x.x.x.x')
elif choice == 3:
credentials('x.x.x.x')
elif choice == 4:
loop = False
print "Closing SSH connection"
print
ssh_close()
else:
raw_input("Wrong option selection. Enter any key to try again..")
You can check the error by running the exe file in command prompt.
This will give you an upper hand.
Especially in cx_freeze you have to mention the dependencies.
I think you are facing some dependency problem.
When you specifiy --debug=all after your pyinstall command when packaging, you will see specific errors when starting your applicataion in the dist folder.
Read here https://pyinstaller.readthedocs.io/en/stable/when-things-go-wrong.html to get more information on debugging specific errors and how to fix them.
you can use the pyinstaller with -F argument to fully package the python interpreter then open windows cmd and run it
pyinstaller -F <your_script>.py
Worry not, my friend! Just add a window.mainloop() call at the end of your program. Then, everything should work properly. I was stumped by the same problem got revelation from your words:
I tried another simple scripts like print function or some math function the executable files work fine
So, I compared both programs side by side and received my answer.
Running pyinstaller with the F flag should solve the problem of immediate close after startup.
Ok so I have code that is supposed to run through a txt file and ping the Ip's if the ping is equal to 0 its does an 'nslookup' on it and then it's supposed to continue but after it does the first one in the terminal it's left on a > as if waiting for input. In other instances, my code runs through the txt file fine but once I added in the 'nslookup' it stops after the first one and waits for input.
Is there a way to make it continue to cycle through the txt file till it gets to the end?
Heres the code I'm using I know there are other ways to do a look up on an Ip address but I'm trying to use 'nslookup' in this case unless its impossible.
import os
with open('test.txt','r') as f:
for line in f:
response = os.system("ping -c 1 " + line)
if response == 0:
print os.system('nslookup')
else:
print(line, "is down!")
that's simply because you forgot to pass the argument to nslookup
When you don't pass any argument, the program starts in interactive mode with its own shell.
L:\so>nslookup
Default server : mydomain.server.com
Address: 128.1.34.82
>
But using os.system won't make you able to get the output of the command. For that you would need
output = subprocess.check_output(['nslookup',line.strip()])
print(output) # or do something else with it
instead of your os.system command
I am trying to create a translator-type program in Python (this is 2.7, if that is important). I want to receive user input, translate it, and then print their output to the screen. That part is not difficult, but I also want to export it to a text file. I am using Powershell for that, with the subprocess module. The Powershell script is very short, and all it does is asks for the user to copy and paste the Python translation into an input. It then calls New-Item to create a file and gives it the value option as the Python translation.
Python code:
def translator:
inquiry = raw_input("Leetspeak trans query: ") #Enter query
inquiry = inquiry.lower() #Change all to lowercase, so that everything gets translated
newPrint1 = "" #The new string that gets returned to them at the end
level = raw_input("What type of 1337 do you want? 1 for basic, 2 for intermediate, \
3 for intermediate-advanced, and 4 for ultimate.")
if level == "1":
from b4s1c_l33t import leetkey
elif level == "2":
from In73rm3d1473_1337 import leetkey
elif level == "3":
from In7_4DV import leetkey
from In7_4DV import combokey
elif level == "4":
from U17IM473_1337 import leetkey
from U17IM473_1337 import combokey
for char in inquiry:
if char in leetkey:
newPrint1 += leetkey[char]
else:
newPrint1 += char #Checks to see if the char is in the single-char list, then appends it accordingly
if int(level) >= 3:
for item in combokey:
if item in newPrint1:
newPrint1 = newPrint1.replace(item, combokey[item])
print newPrint1 #Print answer
question = raw_input(r"Do you want to translate some more? Type Y or N ") #Asks if they want to do more
question = question.lower() #Changes it to lowercase, for sending through the if loop
if question == "y" or question == "Y":
translator() #If answer is yes, program calls the entire function again
elif question != "y" and question != "n" and question != "Y" and question != "N":
print "I didn't quite catch that."
ps = raw_input("Would you like to export your leetness to a file? Type Y or N ")
if ps == "Y" or ps == "y":
import subprocess
subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"./1337Export.ps1\";", "&export"])
else:
print r"0|<. 600|)|3`/3!"
translator() #calls the function once
Powershell script:
Function export(){
$param = Read-Host("Copy-paste the translation from above here! ")
New-Item C:\Scripts\1337\1337ness.txt -type file -value $param
}
But I also know that the script was working perfectly up until I added the Powershell to it, so the problem is either in my usage of the subprocess module or in the Powershell script itself. I am a somewhat-medium-beginner at using Powershell, so any help will be greatly appreciated. Either that, or if there is a way to create the new file and write data to it in Python itself, that would be greatly appreciated.
Thanks,
Prem
Note: in the Python script, the leetkey and combokey are in separate files that are imported based on the value of the variable level.
UPDATE: I looked at the page here, and the subprocess code in the Python script is what I found in that page. It did not work, but instead threw an error saying that the export function does not exist, which it obviously does... in Powershell. Thanks again!
Your parameter construction is off. You want to run the following commandline in PowerShell:
. "./1337Export.ps1"; & export
which basically means "dot-source (IOW import) the script 1337Export.ps1 from the current working directory, then call (&) the function export".
The cleanest way to do this is to put the statement in a scriptblock:
&{. "./1337Export.ps1"; & export}
and pass that scriptblock as a single argument, so your Python statement should look like this:
subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", '-Command', '&{. "./1337Export.ps1"; & export}'])
Of course you need to make sure that 1337Export.ps1 actually exists in the current working directory when you execute the Python script.
You have to do two things:
1) dot source the script (which is similar to python's import), and
2) subprocess.call.
import subprocess
subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"./SamplePS\";", "&export"])
Note: I have assumed that both the .py and .ps1 are residing in the same directory and the name of the powershell script is "SamplePS" and from that script I am using the function "export"
Hope it helps
I am trying to get ryu to run, especially the topology discovery.
Now I am running the demo application for that under ryu/topology/dumper.py, which is supposed to dump all topology events. I am in the ryu/topology direcory and run it using ryu-manager dumper.py. The version of ryu-manager is 2.23.2.
Shortly after starting it gives me this error:
/usr/local/lib/python2.7/dist-packages/ryu/topology/switches.py:478: UserWarning:
Datapath#ports is kept for compatibility with the previous openflow versions (< 1.3).
This not be updated by EventOFPPortStatus message. If you want to be updated,
you can use 'ryu.controller.dpset' or 'ryu.topology.switches'.
for port in dp.ports.values():
What's really weird to me is that it recommends to use ryu.topology.switches, but that error is triggered by line 478 of that very file!
The function in question is this:
class Switches(app_manager.RyuApp):
OFP_VERSIONS = [ofproto_v1_0.OFP_VERSION, ofproto_v1_2.OFP_VERSION,
ofproto_v1_3.OFP_VERSION, ofproto_v1_4.OFP_VERSION]
_EVENTS = [event.EventSwitchEnter, event.EventSwitchLeave,
event.EventPortAdd, event.EventPortDelete,
event.EventPortModify,
event.EventLinkAdd, event.EventLinkDelete]
DEFAULT_TTL = 120 # unused. ignored.
LLDP_PACKET_LEN = len(LLDPPacket.lldp_packet(0, 0, DONTCARE_STR, 0))
LLDP_SEND_GUARD = .05
LLDP_SEND_PERIOD_PER_PORT = .9
TIMEOUT_CHECK_PERIOD = 5.
LINK_TIMEOUT = TIMEOUT_CHECK_PERIOD * 2
LINK_LLDP_DROP = 5
#...
def _register(self, dp):
assert dp.id is not None
self.dps[dp.id] = dp
if dp.id not in self.port_state:
self.port_state[dp.id] = PortState()
for port in dp.ports.values(): # THIS LINE
self.port_state[dp.id].add(port.port_no, port)
Has anyone else encountered this problem before? How can I fix it?
I ran into the same issue (depending on your application, maybe it's not a problem, just a warning that you can ignore). Here is what I figured out after a find . -type f | xargs grep "ports is kept"
This warning is triggered in ryu.topology.switches, by a call to _get_ports() in class Datapath of file ryu/controller/controller.py.
class Datapath(ofproto_protocol.ProtocolDesc):
#......
def _get_ports(self):
if (self.ofproto_parser is not None and
self.ofproto_parser.ofproto.OFP_VERSION >= 0x04):
message = (
'Datapath#ports is kept for compatibility with the previous '
'openflow versions (< 1.3). '
'This not be updated by EventOFPPortStatus message. '
'If you want to be updated, you can use '
'\'ryu.controller.dpset\' or \'ryu.topology.switches\'.'
)
warnings.warn(message, stacklevel=2)
return self._ports
def _set_ports(self, ports):
self._ports = ports
# To show warning when Datapath#ports is read
ports = property(_get_ports, _set_ports)
My understanding is that if the warning is from ryu.topology.switches or ryu.controller.dpset, you can ignore it; because those two classes handle the event for you. But if you use Datapath directly, port status is not updated automatically. Anyone correct me if I'm wrong.
class Switches(app_manager.RyuApp):
#......
#set_ev_cls(ofp_event.EventOFPPortStatus, MAIN_DISPATCHER)
def port_status_handler(self, ev):
I have encountered that problem before but I just ignored it and so far every thing has been working as it was expected.
If you are trying to learn the topology I would recommend using ryu.topology.api. i.e.
from ryu.topology.api import get_switch, get_link
There is this tutorial. However there are some of the stuff missing.
Here is what I have so far: Controller.py
In the Controller.py the two functions get_switch(self, None) and get_link(self, None) would give you list of links and switches.