-2

I'm having difficulty accessing a variable.

I'm working toward the following, calling python script from bash, with arguments, which then imports a function defined in a second python script, executes it and thereby creates a variable which will be used later in the first python script.

At the moment,to test I'm copying and pasting directly into a Python terminal some commands like this:

from script2 import *
foofunction(arg)
print(newlist)

The foo function defined in script2 is executing, I can see files have been written but when I try to print the list supposedly created while executing the imported function, I get a message telling me it's undefined.

Inside my script2.py, i made sure to enter a statement global newlist before defining its length and populating it.

I'm scratching my head at this stage.

5
  • 3
    Please include the relevant code from script2.py :) Commented Jan 18, 2019 at 16:08
  • 2
    Why don't you return newlist in that function and assign it to a variable? Commented Jan 18, 2019 at 16:08
  • 1
    The global keyword does not work that way in python. Have a look here Commented Jan 18, 2019 at 16:11
  • I don't know why that didn't work when I tried it last night, but Graipher's solution is exactly correct. IF you want to throw that into an answer I'll gladly accept it. Commented Jan 18, 2019 at 16:18
  • 2
    from some_module import * is rarely a good practice as it mangles up your namespace. This is a prime example - without the knowledge of script2.py we have no idea whether foofunction and newlist would be a NameError or an object that was defined in script2.py. It's best to be explicit. Commented Jan 18, 2019 at 16:19

1 Answer 1

-2

You should refer to newlist and the module where it is defined like this:

from script2 import *
foofunction(arg)
print(script2.newlist)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.