Python subprocess.call fails on windows without shell=True - python

I am using Python 2.7.14 on windows 10 64bit. I need to use
subprocess.call
but it is failing everytime if I will not pass shell=True. As per the python doc, shell=True should not be used. Also I want to know why it is failing.
python
ActivePython 2.7.14.2717 (ActiveState Software Inc.) based on
Python 2.7.14 (default, Dec 15 2017, 16:31:45) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> subprocess.call(['date'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\subprocess.py", line 168, in call
return Popen(*popenargs, **kwargs).wait()
File "C:\Python27\lib\subprocess.py", line 390, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 640, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
But when run with shell=True, it is running fine
>>> subprocess.call(['date'],shell=True)
The current date is: Wed 12/04/2019
Enter the new date: (mm-dd-yy)
I tried on mac too and subprocess.call is running fine without shell=True
Please help.

date is not an executable, but a builtin function of cmd.exe. You cannot use it outside the shell.

Related

"subprocess.call" doesn't work. error message: "[WinError 193] %1 is not a valid Win32 application" [duplicate]

This question already has answers here:
OSError: [WinError 193] %1 is not a valid Win32 application
(14 answers)
Closed 2 years ago.
my script has to open different kind of scripts (.exe, .py, .c, etc..) and to reach this goal I use these two instructions:
os.chdir(FOLDER_PATH)
os.system("start "+SCRIPT_NAME)
the code works, but it shows the console window whenever os.system("start "+SCRIPT_NAME) is used. to hide it, I read on internet that I have to use the subprocess module. I tried to use these commands but they don't work:
C:\test
λ ls -l
total 16
-rw-r--r-- 1 Admin 197121 13721 Oct 19 00:44 test.py
C:\test
λ python
Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import subprocess
>>> from subprocess import CREATE_NO_WINDOW
>>>
>>> subprocess.call("test.py", creationflags=CREATE_NO_WINDOW)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\subprocess.py", line 340, in call
with Popen(*popenargs, **kwargs) as p:
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\subprocess.py", line 854, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\subprocess.py", line 1307, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
OSError: [WinError 193] %1 is not a valid Win32 application
>>>
how can I solve the issue?
You can use call(), but run() is supposed to be a newer version, and more robust. https://docs.python.org/3/library/subprocess.html Use whichever flavor you like, as long as it achieves your goals.
#! /usr/bin/env python3
import subprocess as sp
cmd = ['echo', 'hi'] ## separate args in list. safer this way
response = sp .run( cmd, stdout=sp.PIPE, stderr=sp.PIPE, encoding='utf-8', creationflags=sp.CREATE_NO_WINDOW)
print( response.stderr, response.stdout )
cmd = 'echo hi' ## alternate string method
response = sp .run( cmd, stdout=sp.PIPE, stderr=sp.PIPE, shell=True, encoding='utf-8', creationflags=sp.CREATE_NO_WINDOW)
print( response.stderr, response.stdout )
If you don't specify encoding, then it returns b'binary encoded strings'

.pyw program crashes upon execution, works as normal .py

I have a python program that I want to run without the console popping up. Naturally I went for a .pyw file to hide the console. However I noticed that after converting the file to a .pyw file. It would crash immediately upon executing.
I have tried uninstalling and reinstalling python and Flask. I ran the program within the Python IDLE and was finally able to get an error readout. I then looked it up and the answer ended up being "you have to run it in py". However the file runs completely fine on my desktop but not on my laptop or any other device that I have tried when set to a .pyw. This is the error traceback:
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
=========== RESTART: C:\Users\emidd\OneDrive\Desktop\FlaskApp.pyw ===========
Traceback (most recent call last):
File "C:\Users\emidd\OneDrive\Desktop\FlaskApp.pyw", line 16, in <module>
app.run()
File "C:\Users\emidd\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\app.py", line 985, in run
cli.show_server_banner(self.env, self.debug, self.name, False)
File "C:\Users\emidd\AppData\Local\Programs\Python\Python37\lib\site-packages\flask\cli.py", line 670, in show_server_banner
click.echo(message)
File "C:\Users\emidd\AppData\Local\Programs\Python\Python37\lib\site-packages\click\utils.py", line 218, in echo
file = _default_text_stdout()
File "C:\Users\emidd\AppData\Local\Programs\Python\Python37\lib\site-packages\click\_compat.py", line 675, in func
rv = wrapper_func()
File "C:\Users\emidd\AppData\Local\Programs\Python\Python37\lib\site-packages\click\_compat.py", line 436, in get_text_stdout
rv = _get_windows_console_stream(sys.stdout, encoding, errors)
File "C:\Users\emidd\AppData\Local\Programs\Python\Python37\lib\site-packages\click\_winconsole.py", line 295, in _get_windows_console_stream
func = _stream_factories.get(f.fileno())
io.UnsupportedOperation: fileno
I know that it can work because I have it running on my desktop, however I am not sure why it works on it but not my laptop. When it works, the readout on the IDLE is "running on http://127.0.0.1:5000/" if anyone could help me get this working with Pythonw that would be great. However it does technically work with normal python.
Try running it on the commandline, IDLE has different IO objects which can mess with it.

Raspberry Pi Radio Transmitter Error

I have read that the Raspberry Pi is capable of transmitting FM.
I have downloaded the script and put on the directory "/home/pi/".
Then I have executed following commands in the terminal over putty:
pi#raspberrypi ~ $ sudo python
Python 2.7.3 (default, Mar 18 2014, 05:13:23)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import PiFm
>>> PiFm.play_sound("left_right.wav")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "PiFm.py", line 7, in play_sound
call(["./pifm", filename])
File "/usr/lib/python2.7/subprocess.py", line 493, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1259, in _execute_child
raise child_exception
OSError: [Errno 13] Permission denied
I have ensured that the soundfile "left_right.wav" is in the same directory.
I don't know why this error is throwed.
I use Raspbian as OS, if this is revelant...
EDIT: The files used are in this download: http://cdn.makezine.com/make/pifm/PiRadio.zip

Python Subprocess not working on Windows 7

Can anyone explain what's happening here? Even built in cmd.exe commands aren't working:
Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:25:23) [MSC v.1600 64 bit (AM
D64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> subprocess.call('dir')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "D:\Python34\lib\subprocess.py", line 535, in call
with Popen(*popenargs, **kwargs) as p:
File "D:\Python34\lib\subprocess.py", line 848, in __init__
restore_signals, start_new_session)
File "D:\Python34\lib\subprocess.py", line 1104, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
>>>
To use 'dir', you have to pass shell=True:
>>> import subprocess
>>> subprocess.call('dir', shell=True)
You have to do this because dir is built into the shell itself, it's not a standalone console application. This is also mentioned in the subprocess.Popen documentation:
On Windows with shell=True, the COMSPEC environment variable specifies
the default shell. The only time you need to specify shell=True on
Windows is when the command you wish to execute is built into the
shell (e.g. dir or copy). You do not need shell=True to run a batch
file or console-based executable.

Cannot use python-nmap

I have multiple times installed python-nmap following the instructions on their site, but it just doesn't work. Every time I try to test it by doing:
>>> import nmap
>>> nm = nmap.PortScanner()
I get the following error:
Python 2.7.4 (default, Apr 19 2013, 18:28:01)
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import nmap
>>> nm = nmap.PortScanner()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "nmap/nmap.py", line 118, in __init__
p = subprocess.Popen(['nmap', '-V'], bufsize=10000, stdout=subprocess.PIPE)
File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1308, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
All help is greatly appreciated. Thanks in advance.
This error is fixed if you install a later version of nmap for python 2.*
Follow the link here: http://nmap.org/book/inst-macosx.html
You need to install nmap by the looks of it

Categories

Resources