我正在使用Python 2.7
我正在尝试从Python运行StatTransfer程序。
当我尝试:
tempname = os.path.abspath('./text.txt')
TEMPFILE = open(tempname, 'wb')
try:
subprocess.check_call('ST convert.stc', shell = True, stdout = TEMPFILE, stderr = TEMPFILE)
except:
raise CritError(messages.crit_error_bad_command)
Run Code Online (Sandbox Code Playgroud)
它失败(CritError是用户定义的)。
追溯不会告诉我任何有用的信息:
Traceback (most recent call last):
File "C:\...\py\run_program.py", line 181, in run_stcmd
run.execute_run(current_directory, posix_command, nt_command)
File "C:\...\py\private\runprogramdirective.py", line 99, in execute_run
raise CritError(messages.crit_error_bad_command)
CritError: 'ERROR! Cannot execute command'
Run Code Online (Sandbox Code Playgroud)
但是将相关行更改为:
subprocess.call('ST convert.stc', shell = True, stdout = TEMPFILE, stderr = TEMPFILE)
Run Code Online (Sandbox Code Playgroud)
它运行成功。
有趣的是,在两种情况下,我的TEMPFILE都显示相同的内容:
|/-|/-|/-|/-|/- |/-|/-|/-|/-|/- Stat/Transfer - Command Processor (c) 1986-2011 Circle Systems, Inc.
www.stattransfer.com
Version 10.1.1866.0714 (32 Bit) - 64 Bit Windows
Serial: ADR4H-L3A3A-N8RJ
User: XXXXXXXXXXX
Your license is in its grace period -- Please call Circle Systems
Your program will die at the end of the month
Status: Temporarily OK (Expired May 31, 2012)
Transferring from SPSS Portable File: ..\orig\10908970\ICPSR_03775\DS0001\03775-0001- Data.por
Input file has 26 variables
Optimizing...
Transferring to Stata: ..\data\ABCFeb.dta
504 cases were transferred(0.02 seconds)
Run Code Online (Sandbox Code Playgroud)
请注意,如果我从Windows命令行运行“ st convert.stc”,它运行得很好,并为我提供了相同的日志消息。它确实实现了convert.stc中编写的内容。
这表明StatTransfer程序是通过subprocess.check_call调用的。但是,最后有一个错误。这是什么错误?如何避免呢?我应该使用2个命令中的哪个?为什么?
ETA:在下面的 mgilson之后,我从 subprocess.call返回值并得到-1。这是什么意思?为什么程序仍然运行,但我似乎没有发现任何真正的错误?
关于如何在这里执行此操作的任何可能的解释和建议?
谢谢。
可能发生的情况是您的进程以非零退出状态退出。要检查,请运行,retcode=subprocess.call(...)
然后打印retcode
。
subprocess.check_call
如果retcode
(以上)为非零,将引发异常。
您看到的异常来自raise subprocess.CalledProcessError
try / except子句中的:
>>> import subprocess
>>> raise subprocess.CalledProcessError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() takes exactly 3 arguments (1 given)
Run Code Online (Sandbox Code Playgroud)
编辑
我仍然会重写try / except子句,因为您捕获了一个异常并引发了另一个异常(这意味着原始消息中的所有信息都丢失了)。
尝试类似:
try:
subprocess.check_call('ST convert.stc', shell = True, stdout = TEMPFILE, stderr = TEMPFILE)
except Exception as e:
raise CritError(messages.crit_error_bad_command+' '+str(e))
Run Code Online (Sandbox Code Playgroud)
这仍然会为您提供原始消息中的一些(不是全部)信息。问题可能仍然是您的子程序正在以非零的退出代码退出。也许没关系(请检查它是否已完成您想要的操作)。
您说可以从命令行运行命令,一切看起来都很好。您还可以通过检查Windows命令行的退出状态来检查行为是否相同(如何从Windows命令行获取应用程序退出代码?)。我猜测退出状态仍为-1-如果不是,则表明您的程序正在与环境(例如环境变量)进行交互,这在您使用python调用时有所不同。
最终,如果程序执行了您想要的操作,并且您不关心退出状态,那么您应该只使用subprocess.call
,但是我建议您查阅程序退出代码的手册,并查看程序的退出状态。 -1实际上表示。