Send cmd in python

Send commands to cmd prompt using Python subprocess module

Edit : sending mutiple commands One way to send multiple commands is to pump them into the child shell’s stdin. Question: using python 3.7 I have the following issue: I wrote a python script in which I open a cmd prompt, do some actions then I want to send some commands to that opened cmd prompt To simplify, it looks something like: All the time the script exits with exception TimeoutExpired , and in the cmd prompt i do not see command written (the input) I looked in the documentation, but i am new with python and did not understood very well how to use the subprocess module Thank you for the support!

Send commands to cmd prompt using Python subprocess module

I have the following issue: I wrote a python script in which I open a cmd prompt, do some actions then I want to send some commands to that opened cmd prompt

To simplify, it looks something like:

import subprocess process = subprocess.Popen(['start','cmd','/k','dir'], shell = True, stdin= subprocess.PIPE, stdout = subprocess.PIPE, text = True) "DO some actions" input = 'date' process.stdin.write(input) process.communicate(input, timeout = 10) 

All the time the script exits with exception TimeoutExpired , and in the cmd prompt i do not see command written (the input)

Читайте также:  Надо ли обновлять java

I looked in the documentation, but i am new with python and did not understood very well how to use the subprocess module

Thank you for the support!

If you want to write something like date in another cmd tab, do like this:

import subprocess input = 'date' subprocess.Popen(['start','cmd','/k','echo',input], shell = True, stdin = subprocess.PIPE, stdout = subprocess.PIPE, text = True) 

Result:

Send commands to cmd prompt using Python, using python 3.7. I have the following issue: I wrote a python script in which I open a cmd prompt, do some actions then I want to send some commands to that opened cmd prompt. To simplify, it looks something like:

Python code to send command through command line

final="cacls " + "E:/" + "\"" + list1[2] + " " + list1[3] + "\"" + " /p " + str os.system(final) 

I am trying to set permission to a folder Using Python but while running this command , User input needs to be provided too i.e

it asks ARE YOU SURE(Y/N) and the user needs to enter «Y» or «N»

Is there any way to use python to send the user input «Y» along with the above code?

 pro = subprocess.Popen(final,shell=True, stdin=subprocess.PIPE) pro.communicate(bytes("Y\r\n",'utf-8')) 

I have added the following code . The program exits without setting the permission.

Try using the subprocess module

import subprocess cmd = ["cacls", "E:/" + list1[2], list1[3], "/p", str] pro = subprocess.Popen(final, stdin=subprocess.PIPE) pro.communicate("y\r\n") 

As a smart programmer, use PBS

from pbs import type as echo# Isn't it echo for Windows? If not, use the correct one script = Command("/path/to/cacls ") print script(echo("Y"), ("E:/" + "\"" + list1[2] + " " + list1[3] + "\"" + " /p " + str).split()) 

Send commands from command line to a running, serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) PORT = 10000 HOST = ‘127.0.0.1’ serversocket.bind((HOST, PORT)) serversocket.listen(10) while 1: #accept connections from outside (clientsocket, address) = serversocket.accept() ct = Thread(target=handle, args=(clientsocket,)) ct.start()

How to send a list of commands using ‘os.system(‘command’)’ to CMD in python

Is it possible to send a list of related commands using os.system() in python? I mean if I want to change current directory to a specific directory and then have a list of contents, how can I do it? (I don’t want to use dir «path» — I want to do both changing current dir, and listing the directories)

Note : It was just an example, I want to know how I can send multiple commands! (Some related commands in a row)

os.system uses the local system shell. You can do it as @Rwaing suggests on many unixy shells but not other places like windows. A better option is subprocess.call and the cwd (current working directory) param

import subprocess subprocess.call('dir', shell=True, cwd='somepath') 

As others have mentioned, if all you really want to do is get a list of the files, the existin python api does it quite well.

Edit : sending mutiple commands

One way to send multiple commands is to pump them into the child shell’s stdin. Its shell dependant, but here’s a windows example:

import os import subprocess as subp p=subp.Popen('cmd.exe', shell=True, stdin=subp.PIPE) p.stdin.write("""dir cd "\\program files" dir """) p.stdin.write('exit' + os.linesep) p.wait() del p print 'done' 

No need for system calls here. os functions chdir and listdir will change your current directory and list the files in a directory respectively.

have a look at os.listdir(path): https://docs.python.org/3/library/os.html#os.listdir

import os entries = os.list.dir('/home/foo') 

How to open a cmd shell in windows and issue, import subprocess process = subprocess.Popen (command, shell=True, stdout=subprocess.PIPE) process.wait () print process.returncode. The command variable should be for example: cmd /k. You can also add a stdin=subprocess.PIPE to the Popen argument list and write commands to cmd: …

How to pass variables from Python to CMD in Windows

I am writing a Python (2.5) script that will search through a folder, grab a specific file, and then pass the file and a command to a CMD shell in Windows. This needs to be done with the command program.exe /rptcsv . Additionally, the .exe HAS to be executed from the C:\Program Files (x86)\Reporter folder, hence the working directory change.

Here’s my problem: I need Python to search for one specific file (fnmatch), and then pass the entire command to a shell. When this is done correctly, the process runs in the background without launching the GUI.
I’ve seen the posts about stdin. stdout, etc, and I don’t need anything piped back- I just need Python to pass the whole thing. Right now what happens is Python launches the GUI but fails to pass the command complete with variables. Is there a way to do this?
I’m still a Python n00b, so please forgive any obvious mistakes.

MC01 = 'WKST01*.bat' MC02 = 'WKST02*.bat' files = os.listdir(FOLDER) MC01_CMD = fnmatch.filter(files, MC01) MC01_CSV = "MC01.csv" exe = ("reporter.exe /rptcsv", MC01_CSV, MC01_CMD) os.chdir("C:\Program Files (x86)\Reporter") os.system("exe") 

Edit: Earlier in my code, I used os.walk in the FOLDER:

print "Walking directory. " for root, dirs, files in os.walk(FOLDER): for file in files: pathname = os.path.join(root, file) 

Because I switched working directories, it’s searching for the MC01_CMD file in C:\Program Files (x86)\Reporter and (of course) it’s not there. Is there a way to join pathname and MC01_CMD without creating a new variable so it’s got the correct location of MC01_CMD?

os.system takes a single string as command. In your case, that is the string «exe» . You need to concatenate the filenames returnd by fnmatch.filter , using » «.join(exe) and then call os.system(command) . Note the missing » in os.system(command) .

For finding the file in a tree, just concatenate the (absolute path of your) base folder of your os.walk call with the basedir and the filename. You can filter on the filenames during os.walk , too.

MC01 = 'WKST01*.bat' MC02 = 'WKST02*.bat' def collect_files(folder, pattern): for basedir, dirs, files in os.walk(folder): for file in fnmatch.filter(files, pattern): yield os.path.join(folder, basedir, file) MC01_CMD = collect_files(FOLDER, MC01) MC01_CSV = "MC01.csv" command = "reporter.exe /rptcsv "+ MC01_CSV + " " + " ".join(MC01_CMD) os.chdir("C:\Program Files (x86)\Reporter") os.system(command) 

Variables aren’t be expanded in string literals. So os.system(«exe») is the same as typing exe in cmd and pressing enter.

So my guess for the correct code would be:

MC01_CSV = MC01 + ".csv" os.chdir("C:\Program Files (x86)\Reporter") os.system("reporter.exe /rptcsv " + MC01_CSV + " " + MC01_CMD) 

It is possible to, I am a beginner in Maya, and I wanted to run commands in a cmd in the active window of maya to modify things in the scene, like put a sphere for example, be in python. from pymel.all import * sphere () or MEL. polySphere -r 1 -sx 20 -sy 20 -ax 0 1 0 -cuv 2 -ch 1; I found the mayapi, and I found several content …

Источник

Execute a Command Prompt Command from Python

Data to Fish

Need to execute a Command Prompt command from Python?

If so, depending on your needs, you may use either of the two methods below to a execute a Command Prompt command from Python:

(1) CMD /K – execute a command and then remain:

import os os.system('cmd /k "Your Command Prompt Command"')

(2) CMD /C – execute a command and then terminate:

import os os.system('cmd /c "Your Command Prompt Command"')

Still not sure how to apply the above methods in Python?

Let’s then review few examples to better understand how to execute a Command Prompt command from Python.

Methods to Execute a Command Prompt Command from Python

Method 1 (CMD /K): Execute a command and then remain

To see how to apply the first method in practice, let’s review a simple example where we’ll execute a simple command in Python to:

  • Display the current date in the Command Prompt
  • The Command Prompt will remain opened following the execution of the command

You may then apply the following code in Python to achieve the above goals:

import os os.system('cmd /k "date"')

Once you run the code in Python, you’ll get the date in the command prompt:

Now what if you want to execute multiple command prompt commands from Python?

If that’s the case, you can insert the ‘&’ symbol (or other symbols, such as ‘&&’ for instance) in between the commands.

For example, what if you want to display all the characters in the command prompt in green and display the current date?

You can then use the following syntax in Python:

import os os.system('cmd /k "color a & date"')

You’ll now see the current date displayed in green:

Note that for more complex commands, you may find it useful to run a batch file from Python.

Method 2 (CMD /C): Execute a command and then terminate

For this method, you can execute the same commands as reviewed under the first method, only this time the Command Prompt will be closed following the execution of the commands.

For example, you may apply the following code in Python to change the color of all characters to green:

import os os.system('cmd /c "color a"')

In this case, the command will still get executed, but you may not be able to see it on your monitor.

In general, you can get a useful legend with further information by typing the command below in the Command Prompt:

Источник

Оцените статью