Enthought canopy validation error - python

I need help!!
I've been struggling with this problem and I cannot seem to solve it.
def itemName():
flag = True
while flag == True:
try:
name = input('What would You like to name it? \n')
Input = str(Input)
print(name)
if name.upper() == ('BOAT') or name.upper() == ('CASUALTY'):
flag = False
else:
raise Exception
except:
print('Boat or Casualty only')
return name
name = itemName()
print(name)
This code will not pass when run. This works in the normal python IDLE but not canopy. Also the print statement only outputs if the input is an integer. I'm stumped, any ideas?

This is python 3 code. Canopy uses Python 2.7
The input function differs between these versions.
In python 2.7, the equivalent is raw_input

Related

How to re-execute same python file [duplicate]

This question already has answers here:
How to make a script automatically restart itself?
(5 answers)
Closed last year.
I've been looking for a way to re-run my program when it reaches the end, it will normally close the file and I need to re-run it manually. I've been trying to replicate making a programming language with my own modules and files because it's had to understand sly,ply and it has alot of functions and every fix I've seen on other stackoverflow pages don't have my fix.
Here is my code:
# main.py
# if program crashes with error code 164 that means it crashed because of invalid syntax or unexpected error in the input you made. contact a developer if you don't know what you did wrong.
import sys
from util.sys import log4javi
from util.sys import *
# Code
print("Running javi build "+build+" ["+lang+"]")
print()
codej = input("Run >> ")
try:
if codej == "":
javi("Null crash", True)
except:
print("excepted null crash")
codej = input("Run >> ")
if codej == "-version":
print(codej)
elif codej == "L":
print("how dare u L me?? >:(")
elif codej == "ඞ":
print("sussy moogus 69420")
print(moogus)
log4javi("Sussy moogus never trust 69420", True)
codej = input("Run >> ")
def sum(num1, num2):
print(num1 + num2)
codej = input("Run >> ")
# The official print statement
def sys_println(printarg):
print(printarg)
codej = input("Run >> ")
try:
exec(codej)
except:
print()
if anyone can give me some help on re-executing it when it reaches the end i will try it.
Python version 3.8.12 64-bit on Ubuntu
I also have alot of functions so I don't know if I can store functions on functions
Actually, it has a simple answer: infinite loops
Just add a while True (or condition with a counter) in your code.
Example:
# imports....
# defs....
while True:
# your code for re-run
# break at some condition; or it can run forever.

Try/Exception giving multiple results in Python

I have this program that should take the user input (an application name installed) and then it will open the application with subprocess.Popen() . All posibles application names are in a dictionary as keys, and the value is the path to the application .exe file. I'm using a try/Exception to see if there will be a KeyError (if the input name doens't exist in the dictionary).
So the programm should take the user input, see if the application name is in the dictionary, and then open the application. If the name isn't on the dictionary, it will give an error message and then ask for a name again.
But when I enter a non-existent name n times, it will run the finally block n times too. How to solve this?
import subprocess
apps ={
"vlc":"app_path\\vlc.exe",
"sublime":"app_path\\sublime_text.exe",
"chrome":"app_path\\chrome.exe",
"opera":"app_path\\launcher.exe",
"torrent":"app_path.\\qbittorrent.exe"
}
def test():
answer = str(input("What program do you want to run: ")).lower()
try:
print(apps[answer])
except KeyError:
print(f"{answer.capitalize()} application unknown. Try again with a valid application name")
print("===============================================================")
test()
except:
print("==============================")
print("Unknown error.")
else:
subprocess.Popen(apps[answer])
finally:
print("===========================================")
print("FINISHED")
test()
You're using recursion here, so obviously the finally block will run as many times as you enter call the function.
The code within finally is always executed regardless if the try block raises an error or not.
W3Schools has good examples for this: https://www.w3schools.com/python/python_try_except.asp
Instead of using try/except, you can simply use a while loop and apps.get(answer, 'ERROR') or if answer in apps to check if the entered input is in the apps dictionary. The following solution may be optimal.
def test():
while True:
answer = input("What program do you want to run: ").lower()
if answer in apps:
try:
res = subprocess.Popen(apps[answer]).communicate()
print("===========================================")
print("FINISHED")
return res
except:
print("==============================")
print("Unknown error.")
else:
print(f"{answer.capitalize()} application unknown. Try again with a valid application name")
print("===============================================================")
test()

Print user input using python

I am trying to print the user input of a package name. I have the following code.
packageList = []
package = input("Enter name: ")
while package == '' :
print("Package name cannot be blank")
packagename = input("Enter name: ")
packageList.append(packageName)
print ((packageName) + "added")
I'm not sure what I'm doing wrong. An error is being displayed: UnboundLocalError: local variable 'packageName' referenced before assignment
Your code is giving you errors because you're mixing up the use of variables package and packageName, when it looks like you should be using the same variable in both places.
The code in aj8uppal's answer corrects most of this (by replacing most references to both variables with packagename), but he never clearly describes that this is the problem (and he still leaves one reference to package in the while condition).
Here's some actually fixed code:
packageList = []
package = input("Enter name: ")
while package == '' :
print("Package name cannot be blank")
package = input("Enter name: ") # assign to package variable here
packageList.append(package) # unindent, and use package again
print ((package) + "added") # use package rather than packageName
Your packageList.append(packageName) should not be in the while loop. Your while loop just makes sure the input is not blank, so we don't want to append it.
What you are doing is not raising the error, so packageName doesn't exist. Therefore, you are printing an uncalled variable.
Also, you call package = input(...), but if there is an error, you call packagename = input(...). You probably want to change that.
Here is your edited code:
packageList = []
packagename = input("Enter name: ")
while package name == '' :
print("Package name cannot be blank")
packagename = input("Enter name: ")
packageList.append(packageName)
print ((packageName) + "added")

Python's psutil module and a bizarre issue

This works perfectly:
def find_processes():
name = "ProcessName.exe"
pid_list = psutil.get_pid_list()
for pid in pid_list:
try:
if str(psutil.Process(pid).name()) == name:
return True
except:
pass
return False
This doesn't:
def find_processes():
name = "ProcessName.exe"
pid_list = psutil.get_pid_list()
for pid in pid_list:
if str(psutil.Process(pid).name()) == name:
return True
return False
It raises an error: AccessDenied: (pid=560)
I'm on a Windows environment and need to access all the processes' names. I already have a working code (the former), so my question is more out of curiosity.
What do the try/except statements do in the first example, and why is it not working if I remove them in the second?
Not all of the information from each process will be available to you unless you are the root user/administrator. See this question: python psutil on windows gives access denied.
You would be better off changing your first example to specifically catch these cases, with:
try:
if str(psutil.Process(pid).name()) == name:
return True
except AccessDenied:
print "Unable to access PID:",pid

Python Precommit hook, Looking at lines for some text

Hello, my question is regarding a Python script I am trying to get to work. The point of this is that when someone makes a SVN Commit they see a login template with four lines: Branch, Bug_Number, Feature affected and Overview. Now I am trying to write a script to make sure that they wrote something on it to make sure no one enters a empty log to commit.
Here is what I have so far in python its based on a old python script.
print "Importing the items"
import re
import sys
import os
print "Initializing the list."
argsList = []
hndFile = open(sys.argv[1],"r")
for line in hndFile:
argsList.append(line)
hndFile.close()
print "Checking what is blank"
faOK = ovOK = False
for line in argsList:
line = line.strip()
if line.startswith('FEATURE_AFFECTED:'):
faOK = line[17:] != ''
if line.startswith('OVERVIEW:'):
ovOK = line[9:] != ''
if not faOK:
print "You Must Enter the Feature Affected"
ret = -1
elif not ovOK:
print "You Must Enter an Overview of the Fix"
ret = -1
else:
ret = 0
print "Finishing the script"
sys.exit(ret)
Any advice would help. I am using Windows XP and currently nothing is happening. I am also using collabnet svn. Currently nothing is happening when I try to run this script. I know I haven't added svnlook in the script I cant really think of where to add and for the variable for it. Thank you.

Categories