回声$?来自python

回声$?来自python,python,linux,Python,Linux,您好,我正在尝试从另一个脚本调用的外部python脚本中获取结果(我知道是1)。什么时候回音$?从命令行我得到1,但当我尝试调用echo$?要从python脚本中获得结果,我在脚本中得到0。这是我的密码: os.system(pythonPath+"serialWait.py "+dev+" "+brate+" login") //this os.system(pythonPath+"serialCommand.py "+dev+" "+brate+" reset") //this work

您好,我正在尝试从另一个脚本调用的外部python脚本中获取结果(我知道是1)。什么时候回音$?从命令行我得到1,但当我尝试调用echo$?要从python脚本中获得结果,我在脚本中得到0。这是我的密码:

 os.system(pythonPath+"serialWait.py "+dev+" "+brate+" login") //this
 os.system(pythonPath+"serialCommand.py "+dev+" "+brate+" reset") //this works      
 value = subprocess.call('echo $?', shell=True)
>//here is where my issue lies I am trying to call the exit code from the previous python script but only get the true value from terminal

这是不可能的:
$?
是一个仅在单个shell期间存在的变量。每次调用
os.system()
,都会创建一个新的shell:旧的shell已经退出,因此该shell内部的变量(如
$?
)不再存在

改用
子流程
模块:

p1 = subprocess.Popen(['serialWait.py', dev, brate, 'login'])
p1.wait()
if p1.returncode != 0:
  print 'Process failed'

如果您只想对任何非零结果抛出异常,请使用
子流程。为此,请检查\u call()

为什么要使用Python使shell运行另一个Python脚本?您不能导入其他模块并从一个脚本运行它们吗?您有3个独立的shell。永远不要使用
os.system()
,一定要使用子流程模块中已有的机制从脚本中获取返回值…@cricket_007我是python新手,但我相信我所做的是可以接受的,因为python脚本是在其他脚本中使用的非常特定的1次运行(即bash中的许多自动化任务)如果您有任何建议,尽管我始终愿意learn@Wooble所以我应该使用子进程?顺便说一句,使用扩展(
.py
或其他)在可执行命令上,无论它们是否用脚本语言编写,都是不好的形式。毕竟,您不运行
ls.elf
。如果您使用setuptools,则setup.py install将创建可执行包装(没有扩展!)非常感谢,现在就试试吧。我在python的第二天做得不错。。。