- Interact with a Windows console application via Python
- Running Python from the Windows Command Line
- 7 Answers 7
- How To Run Python Scripts From the Command Line (Terminal)
- Make Sure Your Terminal or Command Prompt Can Run Python
- Create a Python Script
- Run the Python Script from the Terminal
- There’s More!
- QGIS for Beginners
- Remote Sensing with QGIS
- QGIS Python Scripting with PyQGIS
- Video
- Latest Tutorials
- About Us
Interact with a Windows console application via Python
I am using python 2.5 on Windows. I wish to interact with a console process via Popen. I currently have this small snippet of code:
p = Popen( ["console_app.exe"], stdin=PIPE, stdout=PIPE ) # issue command 1. p.stdin.write( 'command1\n' ) result1 = p.stdout.read() #
I can write to stdin but can not read from stdout. Have I missed a step? I don't want to use p.communicate( "command" )[0] as it terminates the process and I need to interact with the process dynamically over time. Thanks in advance.
Your code seems correct. Does the console_app work ok when you execute from the console? What does it return for command1?
yes console_app works normally when run in cmd.exe It just outputs some numbers based on the input provided (and sometimes strings)
5 Answers 5
Your problem here is that you are trying to control an interactive application.
stdout.read() will continue reading until it has reached the end of the stream, file or pipe. Unfortunately, in case of an interactive program, the pipe is only closed then whe program exits; which is never, if the command you sent it was anything other than "quit" .
You will have to revert to reading the output of the subprocess line-by-line using stdout.readline() , and you'd better have a way to tell when the program is ready to accept a command, and when the command you issued to the program is finished and you can supply a new one. In case of a program like cmd.exe , even readline() won't suffice as the line that indicates a new command can be sent is not terminated by a newline, so will have to analyze the output byte-by-byte. Here's a sample script that runs cmd.exe , looks for the prompt, then issues a dir and then an exit :
from subprocess import * import re class InteractiveCommand: def __init__(self, process, prompt): self.process = process self.prompt = prompt self.output = "" self.wait_for_prompt() def wait_for_prompt(self): while not self.prompt.search(self.output): c = self.process.stdout.read(1) if c == "": break self.output += c # Now we're at a prompt; clear the output buffer and return its contents tmp = self.output self.output = "" return tmp def command(self, command): self.process.stdin.write(command + "\n") return self.wait_for_prompt() p = Popen( ["cmd.exe"], stdin=PIPE, stdout=PIPE ) prompt = re.compile(r"^C:\\.*>", re.M) cmd = InteractiveCommand(p, prompt) listing = cmd.command("dir") cmd.command("exit") print listing
If the timing isn't important, and interactivity for a user isn't required, it can be a lot simpler just to batch up the calls:
from subprocess import * p = Popen( ["cmd.exe"], stdin=PIPE, stdout=PIPE ) p.stdin.write("dir\n") p.stdin.write("exit\n") print p.stdout.read()
Running Python from the Windows Command Line
How do I run a Python file from the Windows Command Line ( cmd.exe ) so that I won't have to re-enter the code each time?
Do you really mean running it under a DOS operating system, or just in the Windows command line interpreter?
7 Answers 7
Wouldn't you simply save your Python code into a file, and then execute that file using Python?
Save your code into a file called Test.py .
$ C:\Python24\Python.exe C:\Temp\Test.py
If you don't want to install an IDE, you can also use IDLE which includes a Python editor and a console to test things out, this is part of the standard installation.
If you installed the python.org version, you will see an IDLE (Python GUI) in your start menu. I would recommend adding it to your Quick Launch or your desktop - whatever you are most familiar with. Then right-click on the shortcut you have created and change the "Start in" directory to your project directory or a place you can mess with, not the installation directory which is the default place and probably a bad idea.
When you double-click the shortcut it will launch IDLE, a console in which you can type in Python command and have history, completion, colours and so on. You can also start an editor to create a program file (like mentioned in the other posts). There is even a debugger.
If you saved your application in "test.py", you can start it from the editor itself. Or from the console with execfile("test.py") , import test (if that is a module), or finally from the debugger.
How To Run Python Scripts From the Command Line (Terminal)
This article will demonstrate how to get a simple Python script running on the command line in a matter of minutes. Once you’ve mastered that, you can get more complicated by passing in required arguments so that your scripts can stand on their own. Once you are comfortable running Python scripts from the command line, continue improving your skills by learning how to pass arguments to your scripts.
Make Sure Your Terminal or Command Prompt Can Run Python
To start, you need to make sure the command line application you are using has access to your Python installation. To do this, open the command prompt, type python and press ‘Enter’. You should see a message that documents the Python version that is being used followed by >>> , which indicates the next code you type will be executed by the Python interpreter. It will look something like this.
Python 3.8.8 (default, Apr 13 2021, 15:08:03) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32 Type "help", "copyright", "credits" or "license" for more information. >>>
If you don’t see something similar, it means that you don’t have Python installed or that the command prompt is not aware of your Python installation.
Create a Python Script
Let’s create a very simple script to demonstrate how this works. This Python script (hello.py) will simply print out a statement that lets us know the code in the script has run, as shown below.
print("Hello from my Python script")
Run the Python Script from the Terminal
Once your Python script is created it’s super easy to run it from the terminal or command line. All you need to do is type python followed by the script name. You’ll need to make sure that your terminal’s working directory is the directory that contains your python script, or give the full path to the script. For example. If I just type python hello.py I get the following error.
python: can't open file 'hello.py': [Errno 2] No such file or directory
There are two ways to fix this.
First, specify the full file path. Like this.
C:\Users\Konrad>python c:/konrad/code/python/z_testing/hello.py Hello from my Python script
You can see that by specifying the full path to the python script that the terminal now knows where to find the file to run and I get the proper output.
Second, use cd to change the terminal’s current directory. Then run the script. Like this.
(base) C:\Users\Konrad>cd c:/konrad/code/python/z_testing (base) c:\konrad\code\python\z_testing>python hello.py Hello from my Python script
By using cd to change the terminal’s directory I no longer need to type the full path to the python script. This is especially useful if you have a number of different scripts in the same directory that you will want to run.
There’s More!
This article gives you a brief, simple introduction to running python scripts from the terminal (or command line). This is a powerful skill to have and there is so much more you can do with it. With a more advanced script, you can pass in parameters/arguments from the command line, which makes it easy to generalize and share your scripts for others to use in various situations. You can check out my guide for passing variables to python scripts from the terminal in this article.
Whether you’re looking to take your GIS skills to the next level, or just getting started with GIS, we have a course for you! We’re constantly creating and curating more courses to help you improve your geospatial skills.
QGIS for Beginners
Remote Sensing with QGIS
QGIS Python Scripting with PyQGIS
All of our courses are taught by industry professionals and include step-by-step video instruction so you don’t get lost in YouTube videos and blog posts, downloadable data so you can reproduce everything the instructor does, and code you can copy so you can avoid repetitive typing
My Recommended Equipment
This article contains affiliate links. When you click on links in this article Open Source Options may make a commission on any sales. This does not have any impact on the price you pay for products.
Video
Konrad has a Master's Degree in Ecology and a Doctorate Degree in Water Resources and has been performing geospatial analysis and writing code (in multiple programming languages) for over a decade. He writes code to develop models and analysis workflows to predict and evaluate changes to landscapes and water resources. He has published multiple articles in prominent peer-reviewed, scientific journals. Konrad's code and workflow contribute to operational products that inform water and ecosystem management.
Latest Tutorials
With QGIS reprojections can be calculated with the export data tool, the reproject layer tool, and GDAL Warp. Reprojecting layers (i.e., converting them to a different coordinate reference system, or.
In cartography and GIS, it is to display two different products side by side to make comparisons. This is a powerful and often necessary feature of any serious GIS software. QGIS makes it possible to.
About Us
We believe data processing and analytics routines should be repeatable without purchasing expensive software licenses. This is possible with open-source programs and programming languages. Our goal is to help you learn open-source software and programming languages for GIS and data science. We do this with free tutorials and paid courses.