I am relatively new to python and have to write a code for a "Countdown" based game; the program would basically ask the user for a word, see whether it is located in a file of words, and if it isn't print (directly after the word input by the user) "is invalid".
Here is the portion of code relative to this (I would supply the whole thing but I'm actually in France so it's in French...)
And here is what I see on my screen now, relative to what I have been asked for.
I'm also new to this forum so apologies in advance if this post isn't as polished as others!
Many thanks in advance to anyone willing to help, it's greatly appreciated!
You could do something like this:
def wordcheck(word):
if ...:
return word + " is valid"
else:
return word + " is invalid"
print("Proposed word: {0} ".format(wordcheck(input())))
Where "if ..." is you checking if the word is valid
So, Python is a general purpose language, and just as any other language, it has nothing to do with the I/O capabilities - those are up to the ambient you are running it.
he built-in "input" has fixed behavior - and unless you change the terminal behavior for things like "turning echo off", it will just proceed to the next terminal line when the user press the return key.
Under Windows, the usual way to get more control over the terminal is to use the msvcrt library - not you'd have to build your own "input" function based on the several character-reading functions there. Actually if you are on Windows, that is likely the way your teacher wants you to follow.
On any other platform, the high-level way to do it is to use the curses library.
I hope you can find your way from there.
Related
For my capstone project, our professor asked us to find an existing project and our job is to fix known issues on it. Our first issue is finding out why difflibs get_close_matches doesn't handle shell commands like pingg well in this program called thefuck on github: https://github.com/nvbn/thefuck/issues/1209
and currently I was working with an addition of it that ignores case seen here:
https://github.com/python/cpython/pull/18983/commits/9953c6e9fa70228be12b361e38607196603177ac
But for the life of me I can't get this thing to work. I don't know if there's a better way to go about it or not but I'm at my wits end.
def get_close_matches(word, possibilities, n=None,cutoff=0.6, ignorecase=True):
"""Overrides `difflib.get_close_match` to control argument `n`."""
if n is None:
n = settings.num_close_matches
return difflib_get_close_matches(word, possibilities, n, cutoff,ignorecase)
Tells me that there's an invalid argument
I'm using pyinstaller to distribute my code as executable within my team as most of them are not coding/scripting people and do not have Python Interpreter installed.
For some advanced usage of my tool, I want to make it possible for the user to implement a small custom function to adjust functionality slightly (for the few experienced people). Hence I want to let them input a python file which defines a function with a fixed name and a string as return.
Is that possible?
I mean the py-file could be drag/dropped for example, and I'd tell them that their user-defined function needs to have a certain name, e.g. "analyze()" - is it now possible to import that from the drag/dropped pythonfile within my PyInstaller Script and use it as this?
I know, it certainly will not be safe/secure and they could do evil things, delete files and so one... But that are things which we don#t care at this point, please no discussions about it. Thanks!
To answer my own question: yes it does actually work to import a module/function from a given path/pythonfile at runtime (that I knew already) even in PyInstaller (that was new for me).
I used this for my Py2.7 program:
f = r'C:\path\to\userdefined\filewithfunction.py'
if os.path.exists(f):
import imp
userdefined = imp.load_source('', f) # Only Python 2.x, for 3.x see: https://stackoverflow.com/a/67692/701049
print userdefined # just a debugging print
userdefined.imported() # here you should use try/catch; or check whether the function with the desired name really exists in the object "userdefined". This is only a small demo as example how to import, so didnt do it here.
filewithfunction.py:
--------------------
def imported():
print 'yes it worked :-)'
As written in the comments of the example code, you'll need a slightly different approach in Python 3.x. See this link: https://stackoverflow.com/a/67692/701049
At the very beginning of the Python Script, I have defined a lot of variables. For instance:
cmd_attack = "attack"
cmd_protect = "protect"
cmd_help = "help"
cmd_help works in a user menu function shown here:
def usermenu():
um_in=raw_input('Menu :: ')
#Help Command
if um_in.lower()==cmd_help.lower():
print(helplist)
usermenu()
That is successful - it prints the help list and then returns to the raw input. However, when I do something similar involving cmd_help in another function...
def tf_elf_battle_merc():
battleinput==raw_input('Elf :: ')
global cmd_help
global cmd_attack
global cmd_protect
if battleinput.lower()==cmd_attack.lower():
attack_merc()
elif battleinput.lower()==cmd_help.lower():
print(tf_elf_help)
That does nothing, prints no errors, and returns to the shell line - without printing anything or going anywhere. I used global commands because I was testing out possible solutions to the problem.
The order that these are put in is the CMD functions at the top, the tf_elf_battle_merc() in the middle, and the usermenu() last. I have tried a few things and the related questions haven't helped... any thoughts? I'm kind of new to Python. If you're curious, it is script where you can log in and play text-type games.
The full script is here on Pastebin.
Thank you in advance!
Edit: If you download and run the script - use "Guest" (case-sensitive) as a username and you'll be let into it
Your code (with some edits, seen below) worked fine for me after changing battleinput==raw_input('Elf :: ') to battleinput=raw_input('Elf ::'), you don't want to compare them, you want to define battleinput.
However, it should raise an error of that, since battleinput is not defined, yet you're trying to comparing it: if battleinput.lower() == ....
Also you're mixing Python 3 and Python 2? Using raw_input() from Python 2, yet print("asd") from Python 3, instead of Python 2's print "asd"?
Everything looks like your code is never reached, the problem is elsewhere.
Here's the code for Python 3, which works fine:
cmd_attack = "attack"
cmd_protect = "protect"
cmd_help = "help"
def tf_elf_battle_merc():
battleinput=input('Elf :: ') # Use raw_input() for Python 2
# You don't need the globals here
if battleinput.lower()==cmd_attack.lower():
print("attack")
elif battleinput.lower()==cmd_help.lower():
print("help")
tf_elf_battle_merc()
Encountered a couple of problems with my python program. Basically, I want to be able to send the path files of multiple images to the command prompt (the user defines how many images, so just putting the direct file paths as args, as below, doesn't do what I want). My code currently looks like this:
os.system("java -jar C:\\Inetpub\\ftproot\\JPivSource\\jpivc.jar image_00000001.jpg image_00000002.jpg image_00000003.jpg")
There are many more images, so of course, writing out image_00000004, 5, 6, etc, is hardly efficient and depends entirely on there being the same number of images each time, which there isn't. (jpivc.jar is the program that opens upon execution of this code, and imports the images and does stuff - that bit works fine). Ideally, the code would be something like:
for i in range(1, NumberOfImages):
os.system("java -jar C:\\Inetpub\\ftproot\\JPivSource\\jpivc.jar image_0000000" + i + ".jpg")
Except, you know, without opening jpivc.jar each time i is incremented, I'm just using the above to show the kind of thing I want. Unfortunately this doesn't work, as it only sends the first part in " " to the command line, if it doesn't give an error message - my first question is, is there any way of making this do what I want it to do? I'm relatively inexperienced at python, so please be as gentle as possible with the technical details.
My second question is - is there a way of then closing either the command prompt or jpivc.jar? I've tried all the predefined functions I can think of - os.system("tskill cmd.exe") and variatons thereupon, os.kill() (although I'm using 2.5, so I'm not surprised this doesn't work), Popen.kill() and Popen.terminate(), and even tried writing my own kill function using ctypes. Nothing works - until either cmd.exe or jpivc.jar are closed manually, then everything in the rest of my code works perfectly. I think Python halts until the command line is closed - which isn't helpful when I want to then close the command line from Python! To sum up; why does it halt like that, and how can I fix it?
More extracts from my code can be provided if needed - I'm using Python 2.5.4 on Windows XP Professional. Don't ask me to provide anything from jpivc.jar - I won't even pretend to understand the slightest bit of Java.
Thanks in advance,
Dave
I believe you are looking for something like this
fileNames=""
for i in range(1, NumberOfImages):
fileNames += "image_0000000%d.jpg "%i
os.system( "java -jar C:\\Inetpub\\ftproot\\JPivSource\\jpivc.jar %s"%fileNames )
Rename your file from script.py to script.pyw to avoid the opening of command prompt.
jpivc.jar will remain open until you close it manually or programmer changes its code to quit after it completes processing all files.
[EDIT]
I found this for starting and killing a process
pidId = os.spawnl(os.P_NOWAIT, "\\windows\\notepad.exe")
import win32api
win32api.TerminateProcess(pidId ,0)
I'm making a text adventure, and I want to have pyGame animations and illustrations and a HUD!
How can I insert this console?
Thanks!
I'm pretty sure that's impossible. If you want a console within a Pygame screen then you'll have to write your own, or find one written by someone else (e.g. http://pygame.org/project-pygame-console-287-.html)
For your game, you can use subsurface, for the different screen 'sections'.
Using python 3x will have issues with multiple libraries, that are not precompiled for you. If you can, it will simplify things to Use 2.7 or 2.6. (There is a python2.7 binary, but not on the front page)
A console isn't too hard. You need to break down the components, deciding what you need.
Start with a miniproject, implementing features one at a time.
keyboard input, print letters to console
render text from a string
blit cached text. will have demo code later, if you are interested
dict() of strings, for commands, with values of function names.
draw the last 10 lines of text
up = scroll through command history
allow command aliases, like "n" and "north" will point to move_north
Implement this using a class: Command() . Which stores a list of all aliases.
commands = { "n" : move_north, "s" : move_south, "fps" : toggle_fps, "help" : print_help }
On enter, call the dict's value, if key exists:
if cmd in commands:
commands[cmd]()
# same as commands["n"]()
You could even have the console's print_help() use the function docstrings.