1

I want to extract a variable named value that is set in a second, arbitrarily chosen, python script.

The process works when do it manually in pyhton's interactive mode, but when I run the main script from the command line, value is not imported.

The main script's input arguments are already successfully forwarded, but value seems to be in the local scope of the executed script.

I already tried to define value in the main script, and I also tried to set its accessibility to global.

This is the script I have so far

import sys
import getopt

def main(argv):
    try:
        (opts, args) = getopt.getopt(argv, "s:o:a:", ["script=", "operations=", "args="])
    except getopt.GetoptError as e:
        print(e)
        sys.exit(2)

    # script to be called
    script = ""

    # arguments that are expected by script
    operations = []
    argv = []

    for (opt, arg) in opts:

        if opt in ("-o", "--operations"):
            operations = arg.split(',')
            print("operations = '%s'" % str(operations))

        elif opt in ("-s", "--script"):
            script = arg;
            print("script = '%s'" % script)

        elif opt in ("-a", "--args"):
            argv = arg.split(',')
            print("arguments = '%s'" % str(argv))

    # script should define variable 'value'
    exec(open(script).read())
    print("Executed '%s'. Value is printed below." % script)
    print("Value = '%s'" % value)

if __name__ == "__main__":
    main(sys.argv[1:])
8
  • 1
    In what way does it fail? Be specific. Error type, message, unexpected behavior, whatever. Commented Apr 23, 2015 at 14:38
  • Have you tried import instead? That's usually safer than exec. Commented Apr 23, 2015 at 14:41
  • @paidhima I edited the question. I meant, that value is not imported. Commented Apr 23, 2015 at 14:44
  • 3
    in case your import needs to be dynamic use impmodule = __import__("modulename") then refer to value via impmodule.value Commented Apr 23, 2015 at 14:45
  • 1
    You could get the value after the exec by using locals()['value'] Commented Apr 23, 2015 at 14:52

3 Answers 3

2

In case your import needs to be dynamic, you can use

impmodule = __import__("modulename") # no .py suffix needed

then refer to value via

impmodule.value 

There are several ways to achieve the same results. See the answers on this topic on SO

Sign up to request clarification or add additional context in comments.

5 Comments

make sure to omit the .py suffix from the module filename you provide as an argument
I used the variable script as argument, so it includes the suffix, is that the error?
yes, I think so. Try hardcoding the module name without .py
@mike: if script.endswith('.py'): script = script[:-3]
The problem seems to be, that the imported script is missing a correctly set environment. It complains that name 'operations' is not defined . There are more arguments that can be set in __import__.
1

The value variable has been put into your locals dictionary by the exec, but was not visible to the compiler. You can retrieve it like this:

print("Value = '%s'" % locals()['value'])

I would prefer an import solution

Comments

1

Using locals() as @cdarke suggested yielded the correct result!

exec(open(script).read())
print("Executed '%s'. Value is printed below." % script)

print("Value = '%s'" % locals()['value'])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.