我编写了一个脚本来扫描文本文件目录,如果找到它们,它会创建一个系统调用来运行txt文件中的脚本。我仍在处理一些小错误,导致我的一些系统调用失败。但是,我想这不要杀死我的剧本。我只想知道错误,然后继续我的生活。似乎任何成功的调用返回0,而导致错误的任何调用返回n。我试图将结果与0进行比较,但它永远不会那么远。关于如何实现这一点的任何建议?
import sys, getopt, os
def main(argv):
def scan_dir(path):
temp_path = path
print temp_path
for file in os.listdir(path):
temp_path += file
if file.endswith(".txt"):
result = os.system("python callscript.py -i %s" % path)
if result != 0
print "Error!"
temp_path = path
def usage():
print "usage: dostuff.py [hi:]\n \
\t -h\t print usage\n \
\t -i\t directory path\n"
sys.exit(2)
if(len(argv) == 0):
usage()
path = ''
try:
opts, args = getopt.getopt(argv,"hi:",["path="])
except getopt.GetoptError:
usage()
for opt, arg in opts:
if opt == '-h':
usage()
elif opt in ("-i", "--ipath"):
path = arg
if path.endswith('/') == False:
path += '/'
scan_dir(path)
if __name__ == "__main__":
main(sys.argv[1:])
答案 0 :(得分:2)
您应该特别使用子进程模块check_call,捕获将为任何非零退出状态引发的CalledProcessError
:
from subprocess import check_call,CalledProcessError
try:
check_call(["python", "callscript.py", "-i",path])
except CalledProcessError as e:
print e.message
不太容易理解你的代码,我建议不要在main中嵌套所有其他函数。我还会使用glob来查找txt文件:
from glob import glob
def scan_dir(path):
files = (os.path.join(path,f) for f in glob(os.path.join(path,"*.txt")))
for fle in files:
try:
check_call(["python", "callscript.py", "-i", fle])
except CalledProcessError as e:
print e.message
def usage():
print "usage: dostuff.py [hi:]\n \
\t -h\t print usage\n \
\t -i\t directory path\n"
sys.exit(2)
if __name__ == "__main__":
args = sys.argv[1:]
if not args:
usage()
path = ''
try:
opts, args = getopt.getopt(args, "hi:",["path="])
except getopt.GetoptError:
usage()
for opt, arg in opts:
if opt == '-h':
usage()
elif opt in ("-i", "--ipath"):
path = arg
if not path.endswith('/'):
path += '/'
scan_dir(path)
答案 1 :(得分:0)
为了在不停止主进程的情况下捕获错误和输出,我建议使用子进程模块。
import subprocess
processToRun = "python callscript.py -i %s" % path
proc = subprocess.Popen (processToRun, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(proc.returncode)
答案 2 :(得分:0)
答案 3 :(得分:0)
我目前的解决方案:
a img { border: none; }
a:hover img { border: none; }