簡體   English   中英

為什么python 2.4一直忽略我的退出功能?

[英]Why does python 2.4 keep ignoring my exit function?

我編寫了僅在2.6或2.7版上運行的腳本。 我進行了安全檢查,以查看是否安裝了其他版本,並檢查是否有可用的兼容版本。 這是我的代碼片段;

# !/usr/bin/python

import sys, os, re
from sys import exit

if sys.version[0:3] in ['2.6', '2.7']:
    import subprocess, datetime, os.path, json, urllib2, socket

def python_version():

    version = sys.version[0:3]

    while version not in ['2.6', '2.7']:

        print '\n\nYou\'re using an incompatible version of Python (%s)' % version

        python_installed_version = []

        for files in os.listdir("/usr/bin/"):  # check to see version of python already on the box

            python_version = re.search("(python2(.+?)[6-7]$)", files)

            if python_version:
                python_installed_version.append(python_version.group())

        if python_installed_version:

            print 'Fortunately there are compatible version(s) installed. Try the following command(s): \n\n',

            for version in python_installed_version:
                print 'curl http://script.py  | %s\n' % version

        sys.exit()

python_version()

with p.stdout:

print 'hello'

當我在python 2.4中運行以上代碼時,出現此錯誤;

  File "<stdin>", line 46
      with p.stdout:
     ^
SyntaxError: invalid syntax

我不明白為什么腳本在檢測到您正在使用sys.exit()使用python 2.4時不立即退出,而是繼續讀取腳本,並在with p.stout:地方給出錯誤with p.stout:被讀取。

我已經刪除了with p.stdout:行,它將正常工作,不會讀取print 'hello' 我不知道為什么with p.stdout:會導致腳本中斷。 這在2.6和2.7上可以正常工作。

關於為什么python 2.4仍然會with p.stdout:行讀取任何想法? 謝謝。

Python 2.4尚不支持with語法,因此該腳本在解析階段而不是在運行時失敗。 您可以通過以下包裝來解決此問題:

if version_check_ok():
    import actual_app
    actual_app.run()
else:
    ...

這樣,只有在您知道這樣做是安全的情況下,才會導入/解析具有新語法的新文件。 但是,您不能將導入移動到版本檢查上方。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM