Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing a variable from one python script to another

I have script1.py which calls script2.py (subprocess.call([sys.executable, "script2.py"]). But script2.py needs variable x that is known in script1.py. I tried a very simple import x from script1, but it seems not to work.

Is that the right approach to use? For example:

#script1.py import subprocess, sys ##subprocess.call([sys.executable, 'C:\\...\\Desktop\\script2.py'], shell=True) ##os.system("C:\\...\\Desktop\\script2.py") subprocess.Popen("C:\\...\\Desktop\\script2.py", shell=True) print "BLAH" x = BO  #script2.py from script1 import x print "HELLO" print x 

All 3 cases of calling script2 (subprocess.call, os.system, subprocess.Popen ) do not work. I get "BLAH" but not "HELLO".

like image 465
Z77 Avatar asked Oct 10 '13 07:10

Z77


People also ask

Can you import variables from another file Python?

First import the file from the current program, then you can import the variable or access the variable in Python. There are three approaches to importing variables from another file. from <file> import * and then use variables directly.

How do you share variables between files in Python?

The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Import the config module in all modules of your application; the module then becomes available as a global name. In general, don't use from modulename import *.


2 Answers

The correct syntax is:

from script1 import x 

So, literally, "from script1.py import the "x" object."

like image 170
TerryA Avatar answered Sep 22 '22 17:09

TerryA


Try this:

from script1 import x 

I just ran the following pieces of code and it worked

script1:

c = 10

script2:

from script1 import c print c 

The second script printed the integer 10 as you should expect.

Oct 17 Edit: As it stands the code will either not produce the "Hello" as indicated or will go into an infinite loop. A couple of issues:

As it stands, BO is undefined. When you execute script1, the subprocess of script2 is opened. When script2 calls script1, it will print out blah but fail on x=BO as BO is undefined.

So, if you fix that by specifying BO with say a string, it will go into an infinite loop (each script calling the other one and printing x, Hello and Blah).

One potential way to fix it is to pass x through a function call. So, script2 could take x as a function parameter and do whatever you need to do with it.

like image 29
ppwt Avatar answered Sep 21 '22 17:09

ppwt