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:])
mike
  • 4,929
  • 4
  • 40
  • 80

3 Answers3

1

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

Community
  • 1
  • 1
Pynchia
  • 10,996
  • 5
  • 34
  • 43
  • make sure to omit the .py suffix from the module filename you provide as an argument – Pynchia Apr 23 '15 at 14:58
  • I used the variable `script` as argument, so it includes the suffix, is that the error? – mike Apr 23 '15 at 15:00
  • yes, I think so. Try hardcoding the module name without .py – Pynchia Apr 23 '15 at 15:02
  • 1
    @mike: `if script.endswith('.py'): script = script[:-3]` – cdarke Apr 23 '15 at 15:03
  • 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\_\_](https://docs.python.org/2/library/functions.html#__import__). – mike Apr 23 '15 at 15:13
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'])
mike
  • 4,929
  • 4
  • 40
  • 80
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

cdarke
  • 42,728
  • 8
  • 80
  • 84