subprocess , opening exe file and using command. python - python

Right now i am using this code to run exe :
subprocess.Popen(['file location,file'],stderr=subprocess.STDOUT,stdout=subprocess.PIPE)\.communicate()[0]
and all goes fine.
But in console i am using additional option to print additional data like
in console: 'exe location' 'file location' option
How to add this option to python script like i am using it right now in console?
I also tried this but not work Opening an .exe and passing commands to it via Python subprocess?
Thanks

You can just add arguments to the list passed as first argument to Popen like so
subprocess.Popen(['file location,file', 'option'])

Related

Running batch file with subprocess.call does not work and freezes IPython console

This is a frequent question, but reading the other threads did not solve the problem for me.
I provide the full paths to make sure I have not made any path formulation errors.
import subprocess
# create batch script
myBat = open(r'.\Test.bat','w+') # create file with writing access
myBat.write('''echo hello
pause''') # write commands to file
myBat.close()
Now I tried running it via three different ways, found them all here on SO. In each case, my IDE Spyder goes into busy mode and the console freezes. No terminal window pops up or anything, nothing happens.
subprocess.call([r'C:\\Users\\felix\\folders\\Batch_Script\\Test.bat'], shell=True)
subprocess.Popen([r'C:\\Users\\felix\\folders\\Batch_Script\Test.bat'], creationflags=subprocess.CREATE_NEW_CONSOLE)
p = subprocess.Popen("Test.bat", cwd=r"C:\\Users\\felix\\folders\\Batch_Script\\")
stdout, stderr = p.communicate()
Each were run with and without the shell=True setting, also with and without raw strings, single backslashes and so on. Can you spot why this wont work?
Spyder doesn't always handle standard streams correctly so it doesn't surprise me that you see no output when using subprocess.call because it normally runs in the same console. It also makes sense why it does work for you when executed in an external cmd prompt.
Here is what you should use if you want to keep using the spyder terminal, but call up a new window for your bat script
subprocess.call(["start", "test.bat"], shell=True)
start Starts a separate Command Prompt window to run a specified program or command. You need shell=True because it's a cmd built-in not a program itself. You can then just pass it your bat file as normal.
You should use with open()...
with open(r'.\Test.bat','w+') as myBat:
myBat.write('echo hello\npause') # write commands to file
I tested this line outside of ide (by running in cmd) and it will open a new cmd window
subprocess.Popen([r'Test.bat'], creationflags=subprocess.CREATE_NEW_CONSOLE)
Hey I have solution of your problem :)
don't use subprocess instead use os
Example :
import os
myBatchFile = f"{start /max} + yourFile.bat"
os.system(myBatchFile)
# "start /max" will run your batch file in new window in fullscreen mode
Thank me later if it helped :)

Fetch PowerShell script from GitHub and execute it

Running into issues executing a PowerShell script from within Python.
The Python itself is simple, but it seems to be passing in \n when invoked and errors out.
['powershell.exe -ExecutionPolicy Bypass -File', '$Username = "test";\n$Password = "password";\n$URL
This is the code in full:
import os
import subprocess
import urllib2
fetch = urllib2.urlopen('https://raw.githubusercontent.com/test')
script = fetch.read()
command = ['powershell.exe -ExecutionPolicy Bypass -File', script]
print command #<--- this is where I see the \n.
#\n does not appear when I simply 'print script'
So I have two questions:
How do I correctly store the script as a variable without writing to disk while avoiding \n?
What is the correct way to invoke PowerShell from within Python so that it would run the script stored in $script?
How do I correctly store the script as a variable without writing to disk while avoiding \n?
This question is essentially a duplicate of this one. With your example it would be okay to simply remove the newlines. A safer option would be to replace them with semicolons.
script = fetch.read().replace('\n', ';')
What is the correct way to invoke PowerShell from within Python so that it would run the script stored in $script?
Your command must be passed as an array. Also you cannot run a sequence of PowerShell statements via the -File parameter. Use -Command instead:
rc = subprocess.call(['powershell.exe', '-ExecutionPolicy', 'Bypass', '-Command', script])
I believe this is happening because you are opening up PowerShell and it is automatically formatting it a specific way.
You could possibly do a for loop that goes through the command output and print without a /n.

Python script writing results to text file

Today I managed to run my first Python script ever. I'm a newb, on Windows 7 machine.
When I run python.exe and enter following (Python is installed in C:/Python27)
import os
os.chdir('C:\\Pye\\')
from decoder import *
decode("12345")
I get the desired result in the python command prompt window so the code works fine. Then I tried to output those results to a text file, just so I don't have to copy-paste it all manually in the prompt window. After a bit of Googling (again, I'm kinda guessing what I'm doing here) I came up with this;
I wrote "a.py" script in the C:/Pye directory, and it looked like this;
from decoder import *
decode("12345")
And then I wrote a 01.py file that looked like this;
import subprocess
with open("result.txt", "w+") as output:
subprocess.call(["python", "c:/Pye/a.py"], stdout=output);
I see the result.txt gets created in the directory, but 0 bytes. Same happens if I already make an empty result.txt and execute the 01.py (I use Python Launcher).
Any ideas where am I screwing things up?
You didn't print anything in a.py. Change it to this:
from decoder import *
print(decode("12345"))
In the Python shell, it prints it automatically; but the Python shell is just a helper. In a file, you have to tell it explicitly.
When you run python and enter commands, it prints to standard out (the console by default) because you're using the shell. What is printed in the python shell is just a representation of what object is returned by that line of code. It's not actually equivalent to explicitly calling print.
When you run python with a file argument, it executes that script, line by line, without printing any variables to stdout unless you explicitly call "print()" or write directly to stdout.
Consider changing your script to use the print statement.:
print(decode("12345"))

Python on Notepad++ : How to pass command line arguments?

"ValueError: need more than 1 value to unpack - Learn Python the Hard Way Ex: 13"
This problem has been discussed a lot of times on this forum. Is there a way to pass on the arguments in the Notepad++ editor itself?
Writing the code in the Notepad++ editor and then executing it on python's default environment after providing the arguments should make this work - but can we directly pass the arguments from notepad++?
P.S - Just started with python - no prior knowledge.
Passing command line arguments can only be done on the command line itself.
Or you can call it via another Python program using os.system to execute command line arguments.
os.system : Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations
import os
os.system("Program_Name.py Variable_Number_Of_Arguements"
You could also use call from subprocess:
from subprocess import call
call(["Program.py", "Arg1", "Arg2"])
Yes, it is possible.
After writing code in Nodepad++, click File > Open Containing Folder > cmd.
This will open up a cmd window where you can type a query like below:
python filename.py arguments

Problem when invoking command prompt from a python script

I would like some help towards invoking a command prompt (& passing some argument to the command prompt) from a python script.
I use pyqt4 for developing the UI and on the UI I have a run button. On selection of run button, I would like to invoke a command prompt and pass on some script name as the argument.
self.connect(run_button, SIGNAL('clicked()'), self.runscript) # this is my run button signal and i'm calling the runscript()
def runscript(self):
print 'Inside Run Script'
os.chdir('C:\PerfLocal_PAL')
try:
subprocess.call(['C:\windows\system32\cmd.exe'])
except:
print 'Exception Caused.'
When I click on run button, the application dies and it does not invoke the command prompt at all. I tried with os.system as well same result.
also, I would like to know how to pass the argument to the call function?
Any help towards this is highly appreciated.
Thanks,
To correctly define file paths in Python on Windows, you need to do one of three things:
Use forward slashes: "C:/PerfLocal_PAL" (Python understands forward slashes regardless of platform)
Use raw strings: r"C:\PerfLocal_PAL"
Escape the backslashes: "C:\\PerfLocal_PAL"
This affects both your chdir call and your subprocess.call invocation.
However, you will also have trouble due to the fact that your parent process is a GUI application, and hence has no console streams for stdin, stdout and stderr. Try using the following instead to get a completely separate command window:
subprocess.call("start", shell=True)
You may also want to use the "/D" argument of start to set your working directory, rather than changing the cwd of the parent process:
subprocess.call(["start", "/DC:\\PerfLocal_PAL"], shell=True)
Have you tried debugging this at all? Which line does the script fail on? Does it actually start the runscript function at all?
Regarding passing arguments to cmd.exe, have a look at the documentation for subprocess.call. It will show you that you can have a second argument providing the command line parameters to the program, e.g.
subprocess.call(["C:\windows\system32\cmd.exe", "scriptname.bat"])
One problem is that subprocess.call will block until it is complete, and cmd.exe will not return until you exit it. That answers the 'just dies' but may not explain the console never appearing. Start with this:
subprocess.Popen(['C:\Windows\system32\cmd.exe'])
That at least will not block. If you can get it to appear, try your arguments, like this:
subprocess.Popen(['C:\Windows\system32\cmd.exe', 'program_or_script', 'arg1'])
Your signal connection and your subprocess call seems to be fine.
Change your chdir call to:
os.chdir(r'C:\PerfLocal_PAL')
I guess the error you are getting is of the form (when you launch your application from the command prompt):
WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: 'C:\PerfLocal_PAL'

Categories