"Subprocess.call" funktioniert nicht. Fehlermeldung: "[WinError 193]% 1 ist keine gültige Win32-Anwendung" [Duplikat]

Nov 25 2020

Mein Skript muss verschiedene Arten von Skripten öffnen (.exe, .py, .c usw.). Um dieses Ziel zu erreichen, verwende ich diese beiden Anweisungen:

  1. os.chdir(FOLDER_PATH)
  2. os.system("start "+SCRIPT_NAME)

Der Code funktioniert, zeigt jedoch das Konsolenfenster an, wann immer os.system("start "+SCRIPT_NAME)es verwendet wird. Um es zu verbergen, habe ich im Internet gelesen, dass ich das subprocessModul verwenden muss. Ich habe versucht, diese Befehle zu verwenden, aber sie funktionieren nicht:

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
>>>

Wie kann ich das Problem lösen?

Antworten

Doyousketch2 Nov 26 2020 at 00:19

Sie können verwenden call(), run()soll aber eine neuere Version und robuster sein.https://docs.python.org/3/library/subprocess.html Verwenden Sie den Geschmack, den Sie mögen, solange er Ihre Ziele erreicht.

#! /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 )

Wenn Sie keine Codierung angeben, werden binär codierte Zeichenfolgen zurückgegeben.