Reputation: 1529
I am trying to run a simple Python script which runs the ipconfig /all
command as a proof of concept.
You can find it below:
from subprocess import PIPE, run
my_command = "ipconfig /all"
result = run(my_command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
print(result.stdout, result.stderr)
But I didn't suceed to run it, I tryed both with the command line and by clicking on it but it open a cmd window for 1 second, and then close it so I cannot even read it.
Edit: I am using Python 3.7 and my script is called ipconfig.py
Upvotes: 1
Views: 22821
Reputation: 41116
Apparently, your problem is not related to the script itself, but rather to Python interpreter invocation. Check [Python 3.Docs]: How do I run a Python program under Windows?.
A general approach would be to:
Launch Python (using its full path: check [Python 3.Docs]: Using Python on Windows for more details) on your module (e.g.):
"C:\Program Files\Python37-64\python.exe" ipconfig.py
Of course, there are many ways to improve things, like adding its installation directory in %PATH% (if not already there) in order to avoid specifying its full path every time 1, but take one step at a time.
On the script side: check [Python 3.Docs]: subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None) (and the examples):
Pass the arguments as a list:
my_command = ["ipconfig", "/all"]
You might also want to check the command termination status (result.returncode
)
1: If you didn't check Add Python 3.7 to PATH when installing it (check image from 2nd URL), you have to add Python's path (C:\Users\USER\AppData\Local\Programs\Python\Python37) manually. There are many resources on the web, here are 3:
Upvotes: 2
Reputation: 86
Your code is working good. The problem is that the cmd closes the window too fast and you can't see the result. Just add a command to wait for your interaction before closing the window.
You can add this at the end of your code:
input("Press Enter to finish...")
Or pause the execution after completion:
import time
[at the end of the code pause for 5 seconds....]
time.sleep(5)
Upvotes: 1