在python解释器中执行多行时出错

时间:2017-03-20 02:55:06

标签: python ubuntu compiler-errors

我正在尝试使用python和良好的编码环境。作为一种解释型语言,我想逐行执行代码并理解在制作脚本之前会发生什么。我尝试在python解释器中运行这个简单的代码。 (我在使用python 2.7的ubuntu上)

public class DeleteConfirmation extends DialogFragment {

    private MainActivity.ContactsAdapter mContactsAdapter;
public Dialog onCreateDialog (Bundle savedInstanceState){
    //Use Builder class because this dialog has a simple Ui
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    //Dialog will have Make a selection as the title

    builder.setMessage("Delete Contact?")

    //An ok button that does nothing

    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            //(HOW TO CALL THE DELETE OR DO DELETING AFTER CLICKING OK???
        }
    })

            // A "Cancel" button that does nothing

    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {


        }
    });


    //Create the object and return it
    return builder.create();



    }//End onCreateDialog
}

这作为脚本执行得非常好。但是当我在翻译上尝试时:

from time import localtime

print ('time is', localtime())

我收到以下错误:

>>> from time import localtime\
... print ('time is', localtime())

当我从终端运行时:

File "<stdin>", line 2
    print(localtime())
        ^
SyntaxError: invalid syntax

我明白了:

$ python test.py

编辑: 第二个代码:

('time is', time.struct_time(tm_year=2017, tm_mon=3, tm_mday=19, tm_hour=20, tm_min=53, tm_sec=11, tm_wday=6, tm_yday=78, tm_isdst=1))

返回:

>>>import os

>>>print os.path.dirname(__file__)

1 个答案:

答案 0 :(得分:0)

  

当您追加此行时会出现此错误   python交互式shell中的os.path.join(os.path.dirname( file ))。

     

Python Shell不会检测文件中的当前文件路径   与您添加此行的文件路径相关

     

所以你应该写这行os.path.join(os.path.dirname( file ))   在file.py.然后运行python file.py,它工作,因为它需要   你的文件路径。   这就是第二个问题的答案。

第一个问题很简单,你忘了括号print(localtime())

>>> from time import localtime
>>> print ('time is ',localtime())
time is  time.struct_time(tm_year=2017, tm_mon=3, tm_mday=20, tm_hour=4, tm_min=32, tm_sec=55, tm_wday=0, tm_yday=79, tm_isdst=0)
>>>