2014-09-03 4435 views
12

我想从子进程的python解释器中调用python文件“hello.py”。但我无法解决这个错误。 [Python 3.4.1]。OSError:[WinError 193]%1不是有效的Win32应用程序

import subprocess  
subprocess.call(['hello.py', 'htmlfilename.htm']) 
Traceback (most recent call last): 
    File "<pyshell#42>", line 1, in <module> 
    subprocess.call(['hello.py', 'htmlfilename.htm']) 
    File "C:\Python34\lib\subprocess.py", line 537, in call 
    with Popen(*popenargs, **kwargs) as p: 
    File "C:\Python34\lib\subprocess.py", line 858, in __init__ 
    restore_signals, start_new_session) 
    File "C:\Python34\lib\subprocess.py", line 1111, in _execute_child 
    startupinfo) 
OSError: [WinError 193] %1 is not a valid Win32 application 

也有任何替代方法“使用参数调用python脚本”,而不是使用子进程? 在此先感谢。

回答

15

错误很明显。文件hello.py不是可执行文件。您需要指定可执行文件:

subprocess.call(['python.exe', 'hello.py', 'htmlfilename.htm']) 

你需要python.exe是搜索路径上可见,或者你会传递的完整路径是运行脚本调用可执行文件:

import sys 
subprocess.call([sys.executable, 'hello.py', 'htmlfilename.htm']) 
+61

“的错误是很清楚。”今天我学到了“清晰”这个词的新含义。 – 2015-08-08 14:33:55

+3

错误消息是esp。 *不清楚,因为由于某种原因它没有将'%1'解析为'hello.py'。 IMO是Python中的一个bug。 – sschuberth 2016-01-07 13:03:00

+0

@sschuberth Python如何做到这一点?遇到错误不是Python。这是'subprocess'模块。它将不得不检查错误代码并仅为此特定错误提供替换字符串。我知道很少有这样的程序。 – 2016-01-07 13:12:39

6

Python安装程序通常会向系统注册.py文件。如果你明确地运行shell,它的工作原理:

import subprocess 
subprocess.call(['hello.py', 'htmlfilename.htm'], shell=True) 
# --- or ---- 
subprocess.call('hello.py htmlfilename.htm', shell=True) 

您可以

C:\>assoc .py 
.py=Python.File 

C:\>ftype Python.File 
Python.File="C:\Python27\python.exe" "%1" %* 
+1

感谢您提醒我,'shell = True'永远是'subprocess'神秘失败的选项!这个问题与我的问题无关(我有一个实际的Windows可执行文件,由于某种原因,它不会运行......如果我使用32位或64位版本的解释器,则无关紧要),但是您的建议是使用'shell = True'的作品! – ArtOfWarfare 2017-01-16 16:18:00

0

我得到了同样的错误,我忘了在subprocess.call使用shell=True检查命令行上的文件关联。

subprocess.call('python modify_depth_images.py', shell=True) 

Running External Command

To run an external command without interacting with it, such as one would do with os.system(), Use the call() function.

import subprocess

Simple command subprocess.call(['ls', '-1'], shell=True)

相关问题