gpt4 book ai didi

python - os.system 调用 python 失败后继续脚本

转载 作者:太空宇宙 更新时间:2023-11-04 03:32:16 25 4
gpt4 key购买 nike

我编写了一个脚本来扫描文本文件目录,如果找到它们,它会创建一个系统调用来在 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:])

最佳答案

您应该特别使用子流程模块 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)

关于python - os.system 调用 python 失败后继续脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30649545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com