Home > Enterprise >  Opening a command window and passing content to it using Python
Opening a command window and passing content to it using Python

Time:10-02

I am currently working with a software package that allows you to create Python scripts and execute them from inside that package. The results of any script are saved back into the program. When the script executes, it does not show a command prompt window.

Is there an easy way to open a command prompt window from inside the script and pass over information for display, such as a dataframe header, a string or a list of values?

I have found from earlier SO posts that I can use:

import os
os.system('cmd /k "Some random text"')

This works as expected, but when I use the following code:

x = str(2 * 2)
output= f'cmd /k "{x}"'

os.system(output)

The number 4 is passed to the command window, but the following message appears:

'4' is not recognized as an internal or external command, operable program or batch file.

CodePudding user response:

The answer is in the question.

'4' is not recognized as an internal or external command, operable program or batch file.

Open cmd and type anything it will give error unless we type something which is recognized by cmd. e.g a help command.

if there is something we want to type in cmd and let it get processed/printed on console we use a command

echo

enter image description here

in your program only the echo command was missing, which will let your output get printed on cmd.

enter image description here

Last but not the least, always remember the ZEN of Python

enter image description here

CodePudding user response:

Use subprocess instead

The `subprocess` has some more benefits compared to `Os`:
  1. The subprocess module provides a consistent interface to creating and working with additional processes.
  2. It offers a higher-level interface than some of the other available modules, and is intended to replace functions such as os.system(), os.spawn*(), os.popen*(), popen2.*() and commands.*().
    enter image description here

    • It opens another cmd tab and passes a command such as echo var.
  • Related