1

my script has to open different kind of scripts (.exe, .py, .c, etc..) and to reach this goal I use these two instructions:

  1. os.chdir(FOLDER_PATH)
  2. 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?

TurboC
  • 777
  • 1
  • 5
  • 19

1 Answers1

0

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'

Doyousketch2
  • 2,060
  • 1
  • 11
  • 11