Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Supported by

[open] Inline Script won't work with loop-element

edited February 2013 in OpenSesame

Hi,

I never used OS before and don't know all functions of Python. Now I wanted to run an experiment, where the data presented is in a .csv-file. With an Inline Script I could read the data and (to test, if the script itself works) write it into a textfile (and yes, it works). But if I try to print the data within a loop-element, there's an error-message that the variables would not exist. (I tried it with "[Phrase1]" (without quotes) as content of a variable of the loop-element.)
Abbridged: I want to read the data line by line from the .csv-file and present it phrase to phrase to the test subjects. After the last phrase is presented, the persons should press a button to decide, if the sentence was correct.
Please help me out. Thanks a lot.

Here's the code (so far):

import codecs

handle_read = open('sentences.csv').readlines()
handle_write = open("sentences.txt","w")
for line in handle_read:
    data= line.split(",")
    id = data[0]
    corr = data[1]
    Phrase1 = data[2]
    Phrase2 = data[3]
    Phrase3 = data[4]
    Phrase4 = data[5]
    Phrase5 = data[6]
    Phrase6 = data[7]
    if corr == "1":
        print Phrase1
        handle_write.write(id+": "+Phrase1+" "+Phrase2+" "+Phrase3+" "+Phrase4+" "+Phrase5+" "+Phrase6+" = correct")
        print 'id+": "+Phrase1+" "+Phrase2+" "+Phrase3+" "+Phrase4+" "+Phrase5+" "+Phrase6+" = correct"'
    else:
        handle_write.write(id+": "+Phrase1+" "+Phrase2+" "+Phrase3+" "+Phrase4+" "+Phrase5+" "+Phrase6+" = not correct")
        print 'id+": "+Phrase1+" "+Phrase2+" "+Phrase3+" "+Phrase4+" "+Phrase5+" "+Phrase6+" = not correct"'

def print_out(id,Phrase1,Phrase2,Phrase3,Phrase4,Phrase5,Phrase6,corr):
    sentence= id+Phrase1+Phrase2+Phrase3+Phrase4+Phrase5+Phrase6+corr
    return sentence

Comments

  • edited 5:25AM

    Sry, I don't know, why the code is disarranged

  • edited February 2013

    Hi Kiri,

    To keep your pasted code readible you could use Markdown syntax as described here:

    When you write your collection of variables to your text file by using

    handle_write.write(id+": "+Phrase1+" "+Phrase2+" "+Phrase3+" "+Phrase4+" "+Phrase5+" "+Phrase6+" = correct")
    

    everything goes well because Phrase1 is a variable that has a certain value assigned to it. This value, for example "This is my first phrase", will be written to your text file.

    In your print statement, however, you (accidentally) make the whole collection a string by starting and ending it with single quotes. A string is not variable (in fact it is a so-called literal constant).

    In short:

    print Phrase1
    

    will print, for example, This is my first phrase, whereas

    print "Phrase1"
    

    will obviously simply print Phrase1.

    So by changing

     print 'id+": "+Phrase1+" "+Phrase2+" "+Phrase3+" "+Phrase4+" "+Phrase5+" "+Phrase6+" = not correct"'
    

    into

     print id+": "+Phrase1+" "+Phrase2+" "+Phrase3+" "+Phrase4+" "+Phrase5+" "+Phrase6+" = not correct"
    

    (and doing the same for your other print statement) your problem should be solved.

    I would advise you to become more familiar with those things if you want to use Python inline coding for your experiments, for example by doing the 'A Byte of Python' tutorial that can be found here:

    Does this answer your question? Best wishes,

    Lotje

    Did you like my answer? Feel free to Buy Me A Coffee :)

  • edited 5:25AM

    Thanks a lot for the fast answer.

    I'll test your suggestion tomorrow.

  • edited 5:25AM

    Hi,

    it still doesn't print out anything and just gives an (Runtime) error message that "Variable Phrase1" wouldn't exist?

  • edited 5:25AM

    Hey Kiri,

    I'm afraid we're going to need a lot more information! In particular,
    We need to know where the error occurs (is it in this inline script item? this piece of code? If so, what does it currently look like? If not, where does the error come from?)

    Could you give some more insight into what your experiment currently looks like?

    As a side note ( but I'm not sure if anything like this is at play here), you said:

    (I tried it with "[Phrase1]" (without quotes) as content of a variable of the loop-element.)

    Please have a look at the osdoc items on variables in opensesame - items vs 'pure' python inline scripting

    You should realize that there's a major difference between opensesame scripting (where the brackets denote an experiment variable that is generally set in a loop-item or so ) and python scripting (which is done in an inline script item, simply to allow for more flexibility in designing experiments, and which uses pure python syntax..).

    For example in python, brackets are not used to denote variables -- so in an inline script,

    [Phrase1]
    

    would be syntactically incorrect

  • edited 5:25AM

    Hi Wouter,

    the error occurs at the end of the experiment. Nothing is printed out during the experiment (neither by inline_script nor by loop). The inline_script works, though. But when then the experiment seems to be interrupted trying to go through the loop-element (which follows the inline_script). Then the runtime error occurs.
    The loop-element obviously can't find the variable "Phrase1" (which is declared in the inline_script, see the code above). So it can't print it out.
    I used the brackets only within the loop-element, because I wanted the loop to print out the content of the variable declared in the inline_script. But even the variable inspector can't find "Phrase1" (or another Phrase) of the inline_script. The brackets are not used in the inline_script itself.

    I hope, my explanation helped you to understand my problem.

  • edited March 2013

    Hi Kiri,

    The loop-element obviously can't find the variable "Phrase1" (which is declared in the inline_script, see the code above). So it can't print it out. I used the brackets only within the loop-element, because I wanted the loop to print out the content of the variable declared in the inline_script. But even the variable inspector can't find "Phrase1"

    By declaring/defining a variable within an inline script the way you have done above, i.e. within a python inline script, it is only visible/accessible within that particular inline script.

    To make it visible to other inline scripts somewhere else in the experiment, you could either declare the variable global (the link is about functions, but it works the same for variables)

    Another (possibly better) option would be, to store them within the experiment object using:

    exp.Phrase = 'something' # equivalent to  self.experiment.Phrase = ...
    # ...and in another inline script item use e.g. "var = exp.Phrase" to retrieve value
    

    OR (which seems to be what you need here) :

    exp.set('Phrase', 'something') #note the quote chars around the variable name
    # ... and use "var = exp.get('Phrase')" to retrieve them later.
    

    The latter option has the main advantage that you can not only retrieve the variable in inline_script items, but also from gui items using the bracket notation [Phrase], as well as it being logged by the logger item (...and probably found by the variable inspector as well?).

    For that reason, it also has to be a variable that can be logged by the logger item. That's why the exp.get() way of doing things is only used for primitive variable types, such as numbers and strings. It is not suitable for passing around lists and dictionaries and such (but for those you can use global or the first method)

    I hope this helps!

    For more info, you could read :

    EDIT: as I typed the above, it still wasn't fully clear to me what you wanted to do with the variable within the loop element: but do you mean you want to use one of the phrases read in from a file as the value of a particular variable within the loop table? In that case, the above still holds, but a lot of my explanation may have been a bit unclear. Is this what you want?

  • edited 5:25AM

    Hi Wouter,

    yes, I wanted (all) the phrases (1-6) to be read within the loop table (I couldn't explain it better, sry for that). Thank you very much for your answer. I'll test it as soon as possible but it seems to be the right way. I'll tell you if it worked.

  • edited 5:25AM

    Hi,

    I tested it. Now the variables are finally shown in the variable inspector - so far so good, thank you very much for your help.
    But unfortunately they still aren't printed out?

  • edited 5:25AM

    Hi Kiri,

    What do you mean exactly by 'printed out'?

    In Wouter's example experiment, the in-the-loop-item defined variable 'bla' is printed out, isn't it? This is done by the line

    print exp.get('bla')
    

    which he placed in the Run phase of his second inline_script item.

    As a result, the value of 'bla', in this case "This is a phrase read in from a file", is printed to the debug window. To view the debug window, simply click the red ladybug item in the main toolbar.

    The value of the variable 'bla' is also presented to the participant by the sketchpad item, where Wouter used the square-bracket method ([bla]) to display the phrase ("This is a ...") on screen.

    Is one of those two what you meant by 'printed out'?

    I would advise you to walk through the step-by-step tutorial to familiarise yourself with OpenSesame:

    Also, if you're planning to use Python inline coding for your experiments, walking through a Python tutorial might be a good idea as well:

    Have a good evening!

    Lotje

    Did you like my answer? Feel free to Buy Me A Coffee :)

  • edited 5:25AM

    Hi Lotje,

    I meant that the experiment starts, doesn't do anything, ends and shows the error message. Thanks for the links. I think they'll help me too.

    Have a good weekend.

    Kiri

  • edited March 2013

    Hi Kiri,

    Does this happen when you run Wouter's experiment? Or your own script?

    Are you sure you set your variable (say, 'sentence') like so:
    exp.set("sentence', sentence)
    and then refer to it in your loop item like so:
    [sentence]?

    And did you set your variable in the prepare phase tab of the inline_script item? (Otherwise the variable is indeed not yet available when the loop item is ran.)

    If those suggestions don't solve your problem, perhaps you could upload your experiment here or copy your up-to-date inline_script, such that we could have a closer look. Also, could you please provide us with the error message as shown in the debug window? (To view the debug window, simply click the red ladybug icon in the main toolbar.)

    Best,

    Lotje

    Did you like my answer? Feel free to Buy Me A Coffee :)

  • edited 5:25AM

    Hi Lotje,

    I set the variables as described (with exp.set("abc", abc)) within the prepare phase tab of the inline_script item and within the loop item also as described. The variable inspector now shows the variables declared by me, but I can't use their content. I'll load up the error message on Friday (I'm using another PC at the moment).

    Greetings,

    Kiri

  • edited 5:25AM

    Hi,

    as promised, here is the error message from Debug Window:

    Python 2.7.3
    Type "help()", "copyright()", "credits()" or "license()" for more information.
    Type "modules()" for details about installed modules and version information.
    Use the "print [msg]" statement in inline_script items to print to this debug window.
    
    openexp._canvas.psycho.init_display(): window type = pyglet
    openexp._canvas.psycho.init_display(): waitblanking = True
    openexp._canvas.psycho.init_display(): monitor = testMonitor
    openexp.sampler._legacy.init_sound(): sampling freq = 48000, buffer size = 512
    openexp.sampler._legacy.init_sound(): mixer already initialized, closing
    experiment.init_log(): using 'D:\quickrun.csv' as logfile (utf-8)
    experiment.run(): experiment started at Fri Mar 22 10:48:09 2013
    Traceback (most recent call last):
      File "dist\libopensesame\inline_script.py", line 111, in prepare
      File "<string>", line 17, in <module>
    NameError: name 'Phrase1' is not defined
    12.7800 ERROR   avbin.dll failed to load. Try importing psychopy.visual as the first
        library (before anything that uses scipy) and make sure that avbin is installed.
    12.8715 WARNING Use of rgb arguments to stimuli are deprecated. Please use color and colorSpace args instead
    
    13.8037 WARNING Couldn't measure a consistent frame rate.
      - Is your graphics card set to sync to vertical blank?
      - Are you running other processes on your computer?
    

    Additionally there's the message (which pops up) telling me that theres the
    Error: Inline script error
    In: inline_script (prepare phase)
    Line: 17 (which is the line where I typed "print Phrase1" to test the variable)

    Python traceback:
    NameError: name 'Phrase1' is not defined.

    I also tried to comment out this line, but it gives me the same error message with other lines. Except for the error message at the end, nothing is shown during the 'running' experiment.

    Hope, that's what you wanted.

    Greetings,

    Kiri

  • edited March 2013

    Hi Kiri,

    Are you trying to print the variables in a different inline_script than the inline_script where you defined them? (Note that even the Run phase tab of the same item is considered as a different inline_script.)

    To make variables available in other inline_script items, you should make them global like so:

    global Phrase1, Phrase2, Phrase3, Phrase4, Phrase5, Phrase6
    

    After doing so, you should be able to use the variables in another inline_script, for example to print them to the debug window:

    Print "The first sentence is ", Phrase1
    

    So, the code where you define the variables should look something like this:

    # Read information from the file:
    
    path = exp.get_file('sentences.txt')
    
    handle_read = open(path).readlines()
    
    for line in handle_read:
        data = line.split(",")
        id = data[0]
        corr = data[1]
        Phrase1 = data[2]
        Phrase2 = data[3]
        Phrase3 = data[4]
        Phrase4 = data[5]
        Phrase5 = data[6]
        Phrase6 = data[7]
    
    # To make the variables available in the interface,
    # such as a loop item, set the variables 
    # by using the exp.set() function:
    exp.set("Phrase1", Phrase1)
    exp.set("Phrase2", Phrase2)
    exp.set("Phrase3", Phrase3)
    exp.set("Phrase4", Phrase4)
    exp.set("Phrase5", Phrase5)
    exp.set("Phrase6", Phrase6)
    
    # If you want the variables to be available in other
    # inline_script items as well, you should make them
    # global, like so:
    global Phrase1, Phrase2, Phrase3, Phrase4, Phrase5, Phrase6
    

    I uploaded an example experiment here:

    This example should give you an idea of how to read sentences from a text file and use them for stimulus presentation in a loop item. To download the example experiment:

    • Download the script and change the extension to 'opensesame.tar.gz' (instead of '.txt').
    • Now you can open the experiment as normally.
    • Add a text file with the sentences to the filepool (and call this file 'sentences.txt' or change the code according to your filename).

    I hope this helps!

    Best,

    Lotje

    Did you like my answer? Feel free to Buy Me A Coffee :)

  • edited 5:25AM

    Hi Lotje,

    thank you very very much. The example experiment was very helpful. Now the experiment is doing what I wanted it to do.

    Have a good weekend and Happy Easter.

    Greetings,

    Kiri

  • edited 5:25AM

    Hi Kiri,

    I'm glad to hear! Feel free to post any further questions you may have.

    A happy Easter to you too!

    Lotje

    Did you like my answer? Feel free to Buy Me A Coffee :)

Sign In or Register to comment.

agen judi bola , sportbook, casino, togel, number game, singapore, tangkas, basket, slot, poker, dominoqq, agen bola. Semua permainan bisa dimainkan hanya dengan 1 ID. minimal deposit 50.000 ,- bonus cashback hingga 10% , diskon togel hingga 66% bisa bermain di android dan IOS kapanpun dan dimana pun. poker , bandarq , aduq, domino qq , dominobet. Semua permainan bisa dimainkan hanya dengan 1 ID. minimal deposit 10.000 ,- bonus turnover 0.5% dan bonus referral 20%. Bonus - bonus yang dihadirkan bisa terbilang cukup tinggi dan memuaskan, anda hanya perlu memasang pada situs yang memberikan bursa pasaran terbaik yaitu http://45.77.173.118/ Bola168. Situs penyedia segala jenis permainan poker online kini semakin banyak ditemukan di Internet, salah satunya TahunQQ merupakan situs Agen Judi Domino66 Dan BandarQ Terpercaya yang mampu memberikan banyak provit bagi bettornya. Permainan Yang Di Sediakan Dewi365 Juga sangat banyak Dan menarik dan Peluang untuk memenangkan Taruhan Judi online ini juga sangat mudah . Mainkan Segera Taruhan Sportbook anda bersama Agen Judi Bola Bersama Dewi365 Kemenangan Anda Berapa pun akan Terbayarkan. Tersedia 9 macam permainan seru yang bisa kamu mainkan hanya di dalam 1 ID saja. Permainan seru yang tersedia seperti Poker, Domino QQ Dan juga BandarQ Online. Semuanya tersedia lengkap hanya di ABGQQ. Situs ABGQQ sangat mudah dimenangkan, kamu juga akan mendapatkan mega bonus dan setiap pemain berhak mendapatkan cashback mingguan. ABGQQ juga telah diakui sebagai Bandar Domino Online yang menjamin sistem FAIR PLAY disetiap permainan yang bisa dimainkan dengan deposit minimal hanya Rp.25.000. DEWI365 adalah Bandar Judi Bola Terpercaya & resmi dan terpercaya di indonesia. Situs judi bola ini menyediakan fasilitas bagi anda untuk dapat bermain memainkan permainan judi bola. Didalam situs ini memiliki berbagai permainan taruhan bola terlengkap seperti Sbobet, yang membuat DEWI365 menjadi situs judi bola terbaik dan terpercaya di Indonesia. Tentunya sebagai situs yang bertugas sebagai Bandar Poker Online pastinya akan berusaha untuk menjaga semua informasi dan keamanan yang terdapat di POKERQQ13. Kotakqq adalah situs Judi Poker Online Terpercayayang menyediakan 9 jenis permainan sakong online, dominoqq, domino99, bandarq, bandar ceme, aduq, poker online, bandar poker, balak66, perang baccarat, dan capsa susun. Dengan minimal deposit withdraw 15.000 Anda sudah bisa memainkan semua permaina pkv games di situs kami. Jackpot besar,Win rate tinggi, Fair play, PKV Games