Python, Command Line, Windows - python

NEW Edit. I am using Python2.7.5 in Windows 7. I'm new to command line arguments. I am trying to do this exercise:
Write a program that reads in a string on the command line and returns a table of the letters which occur in the string with the number of times each letter occurs. For example:
$ python letter_counts.py "ThiS is String with Upper and lower case Letters."
a 2
c 1
d 1
# etc.
I have some fundamental problems: How do I add strings to the command line?
I went to Control Panel and altered the Path (adding ;C:\Python27)
Now I'm in cmd.exe
This gets the right answer
>>>python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
However these get SyntaxError: invalid syntax:
python letter_counts.py
C:\Python27\python.exe
C:\Python27\pythonw.exe
C:\Python27\python.exe .\letter_counts.py
Any suggestions? thank you!

In response to your question on 'adding strings to the command line'.
import sys
print sys.argv
will give you the command line args you passed in. In your case, it looks like you want the first argument, so you would do something like:
print sys.argv[1]
note that sys.argv[0] will give you the filename you passed into python, so you actually want [1] in this case.
I don't use Windows, but if you want an easy setup python environment you could look into ActivePython perhaps. Worst case or as a temporary solution you could just go to the folder where python.exe is located and run your scripts there.

After modifying your path, did you start up a new instance of the command prompt (this has caused me much grief in the past)? To check if your path change was successful:
echo %PATH%
and check to see if C:\Python2.7.5 was appended to it.
If not then run:
set PATH=%PATH%;C:\Python2.7.5
To call a python script with a command line argument (assuming that your script is in the current working directory):
python letter_counts.py "Your Text Goes Here"
OR if you just want to be overly verbose (or your PATH still isn't right):
C:\Python2.7.5\python.exe .\letter_counts.py "Your text still goes here"
EDIT:
Make sure you are doing this from the command prompt and not the python interpreter. To access the command prompt you can hit:
1. Windows Key + R
2. type "cmd" (without quotes) and hit enter

Related

Redirect Python Print & Input Calls to ConEmu (or similar program)

ORIGINAL QUESTION
Printing unicode character \u0332 to command prompt with python results in an underscore after the previous letter, not underneath.
I ran chcp 65001 based on some suggestions I found on the web, it displays properly neither before nor after running that command.
Example:
C:\>python
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print(u"this is a te\u0332st.")
this is a te_st.
Expected output:
this is a te̲st.
(note: copy pasting the output from console to here displays the character correctly, as seen in expected output)
EDIT 1:
It seems that no unicode combine characters are displaying combined in the command prompt.
NEW QUESTION BASED ON COMMENTS BY #ErykSun
Is there a simple way to either redirect python print and input calls to ConEmu (or similar program), or write custom functions that replace them?
EDIT 1:
Based on the suggestion from #lenz, is there a way to run ConEmu and pass it a command to run from a command?
Thanks to #ErykSun's comments, I've set my default terminal to ConEmu which displays unicode combined character correctly.
To future users looking for an answer to this question, assuming you're using ConEmu you can set it to the default console by doing this:
right click the top bar and go to Settings... (or use the keyboard shortcut Win+Alt+P)
go to Intergration -> Default term in the left menu
Check the following boxes:
Force ConEmu as default terminal for console applications, Register on OS startup, Leave in TSA, and Aggressive mode
Then hit Save settings

How to stop a Python script but keep interpreter going

I have a Python script, and I want to execute it up to a certain point, then stop, and keep the interpreter open, so I can see the variables it defines, etc.
I know I could generate an exception, or I could invoke the debugger by running pdb.set_trace(), then stop the debugger, which is what I currently use.
...but is there a command that will just stop the script, as if it had simply reached its end? This would be equivalent to commenting the entire rest of the script (but I would not like doing that), or putting an early return statement in a function.
It seems as if something like this has to exist but I have not found it so far.
Edit: Some more details of my usecase
I'm normally using the regular Python consoles in Spyder. IPython seems like a good thing but ( at least for the version I'm currently on, 2.2.5) some of the normal console's features don't work well in IPython (introspection, auto-completion).
More often than not, my code generates matplotlib figures. In debug mode, those cannot be updated (to my knowledge), which is why I need to get completely out of the script, but not the interpreter).
Another limit of the debugger is that I can't execute loops in it: you can copy/paste the code for a loop into the regular console and have it execute, but that won't work in the debugger (at least in my Spyder version).
If you invoke your program with python -i <script>, the interpreter will remain active after the script ends. raise SystemExit would be the easiest way to force it to end at an arbitrary point.
If you have ipython (highly, highly recommended), you can go to any point in your program and add the following lines
import IPython
IPython.embed()
Once your program reaches that point, the embed command will open up a new IPython shell within that context.
I really like to do that for things where I don't want to go the full pdb route.
If you are using the Python Shell, just press CTRL + C to throw a KeyboardInterrupt. You can then check out the state of the program at the time the exception was throw.
x = 0
while True:
x += 1
Running the script...
Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
Traceback (most recent call last):
File "C:/Python27/test.py", line 2, in
while True:
KeyboardInterrupt
>>> x
15822387

What is calculator mode?

I don't know about the meaning of calculator mode in Python, and I've put the portion of documentation below.
If you quit from the Python interpreter and enter it again, the definitions you have made (functions and variables) are lost. Therefore, if you want to write a somewhat longer program, you are better off using a text editor to prepare the input for the interpreter and running it with that file as input instead. This is known as creating a script. As your program gets longer, you may want to split it into several files for easier maintenance. You may also want to use a handy function that you’ve written in several programs without copying its definition into each program.
To support this, Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in calculator mode).
(Emphasis mine)
Here's the original document.
Interactive mode and Calculator mode are the same thing. This is a mode that comes with Python. If you have installed Python then you have also installed something called the Python Shell.
There are two ways you can access the Python Shell:
Typing python or python[version-number] in your command
prompt/terminal window:
Assuming that you have python in your PATH variable, you can access
the Python Shell by simply typing python or python[version-number]
in your command prompt/terminal window.
Running the Python Shell in the Python IDLE(Integrated Development Environment) GUI:
To run the Python Shell in the Python IDLE GUI, you can type(again i'm assuming that the path to your python installation folder, is in your PATH variable), just type idle into your command prompt\terminal window and this should start the Python Shell in the Python IDLE GUI.
Of course the exact text for the Python Shell heading will vary between OS's, but all of them look very similar. Here is an example of what the heading appears like on my Mac:
Python 2.7.5 (default, Mar 9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
As you can tell from the text above, a newline in the Python Shell is denoted by three caret symbols: >>>. For each newline three new carets are printed. Using Python Shell is different from typing a script because the script is predefined and the shell is written line-by-line.
Here is an example to illustrate my point further:
>>> xyz = 100
>>> for i in range(1, 10):
... xyz += i
... print(xyz)
...
101
103
106
110
115
121
128
136
145
As you can tell from the above program, indention is noted by three dots: ..., and the only time the Python Shell shows only one line at a time unless it is 'echoing' back what you typed in.
Why is it called interactive?
One of the main reason it's called interactive is that to display variable values or run the module in general you don't have to explicitly invoke the Python interpreter. Take the example below:
>>> name = "some name"
>>> print(name)
some name
>>> name
'some name'
As displayed above, you can access the values of a variable without needing to call print on the variable. This can be very useful when debugging or trying to understand your code.
The Python Shell is not really a practical way to write long/complex programs. A better choice would be to use the Python IDLE built-in script editor or another text-editor or IDE.

How to make shortcut work from PATH

I have two versions of Python on Windows and want to use them through cmd. I tried to make shortcuts of their python.exe and renaming them to python26 and python33 (I also added their locations to PATH), but unfortunately this does not work. Calling python26 or python26.lnk outputs in not recognized as an internal command.
Is there any other way to do it (like Linux virtualenv), or I missed something in my idea ?
Create a new .bat file under C:\imagaginary_path\ and name it python2.bat.
Within the bat file write:
C:\Python26\python.exe %*
Then create another one under C:\imagaginary_path\ and name it python3.bat.
With the content:
C:\Python33\python.exe %*
Now remove C:\Python26\ and C:\Python33\ from your PATH and instead place C:\imaginary_path\ in your PATH variable.
There, Windows treats .bat files as executables, and now you can call python2 test.py
Now every time you press Ctrl+C You will get a promt asking "Terminate batch job ?" which is kind of annoying, there's a few alternatives in order to solve this and one being you edit your python2.bat to look like:
start C:\Python26\python.exe %*
As others have mentioned, creating a batch file works fine. But if you still want to use normal shortcuts (.lnk files) you can modify your PATHEXT environment variable to include .LNK. This variable tells Windows what extensions to treat as executable files when searching through the PATH variable.
For example, after creating a shortcut and adding its folder to PATH, this works:
C:\>python27
'python27' is not recognized as an internal or external command,
operable program or batch file.
C:\>echo %PATHEXT%
.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
C:\>set PATHEXT=%PATHEXT%;.LNK
C:\>python27
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> ^Z
C:\>
You could also work with Windows path:
set path=C:\Python26;.;..;C:\windows;C:\windows\system32
prompt $ & start title Python26
Save this as Py26.bat and type Python in the screen that displays
set path=C:\Python33;.;..;C:\windows;C:\windows\system32
prompt $ & start title Python33
Save this as Py33.bat and type Python in the screen that displays
Instead of creating shortcuts, what you could do is to change the name of python.exe itself.
So you could rename the python.exe in C:\Python26\ to 'python2', and the python.exe in C:\Python33\ to 'python3'. Given that most of the Python code right now is in < Python3, an efficient alternative would be to just change the Python 3.3 python.exe file to be 'python3', and leave the Python 2.6 one unchanged. This way, you would be able to specify if you wanted to run something using python3.
Now edit the %PATH% environment variable to include both C:\Python26\ and C:\Python33.
Example:
python3 chunky_bacon_FTW.py
would run using Python3.3.

How to launch a Python file on Windows 7?

this is the first time I have used Python.
I downloaded the file ActivePython-2.7.1.4-win32-x86
and installed it on my computer; I'm using Win7.
So when I tried to run a python program, it appears and disappears very quickly. I don't have enough time to see anything on the screen. I just downloaded the file and double-cliked on it.
How do I launch this file? I know that it is a long file for a first Python tutorial.
Add the line
input()
to the end of the program, with the correct indentation. The issue is that after the data is printed to the console the program finishes, so the console goes away. input tells the program to wait for input, so the console won't be closed when it finishes printing.
I hope you're not using that program to learn Python; it's pretty complicated!
go to Start > All programs > Accessories and click on Command Prompt. then drag the python file from the explorer view into this command line and press Enter...
now you can watch the output of the script execution !
run it from a command prompt:
> python myscript.py
You can also start only the python interpreter from the command prompt (or by running python.exe) and then try some commands:
> python
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
>>> a = 2
>>> b = 7
>>> print a+b
9
>>>
Or run it from a batch file:
myprog.py
pause
Has the advantage that you can specify a different version of Python too.
Just a bit more on this.
You have a script myscript.py in a folder C:\myscripts. This is how to set up Windows 7 so that you can type > myscript into a CMD window and the script will run.
1) Set your PATH variable to include the Python Interpreter.
Control Panel > System and Security > System > Advanced Settings > Environment Variables. You can set either the System Variables or the User Variables. Scroll down till you find PATH, select it, click Edit.The Path appears selected in a new dialog. I always copy it into Notepad to edit it though all you need do is add ;C:\Python27 to the end of the list. Save this.
2) Set your PATH variable to include C:\myscripts
3) Set your PATHEXT variable to include ;.PY. (This is the bit that saves you from typing myscript.py)
This may now just work. Try opening a command window and typing myscript
But it may not. Windows can still mess you about. I had installed and then uninstalled a Python package and when I typed myscript Windows opened a box asking me which program to use. I browsed for C:\python27\python.exe and clicked that. Windows opened another command window ran the script and closed it before I could see what my script had done! To fix this when Windows opens its dialog select your Python and click the "Always do this" checkbox at the bottom. Then it doesn't open and close another window and things work as they should. Or they did for me.
Added: Above does not say how to pass arguments to your script. For this see answer Windows fails to pass arguments to python script

Categories