Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

Pass variable between python scripts

I'm sure this is very simple but I've been unable to get it working correctly. I need to have my main python script call another python script and pass variables from the original script to the script that I've called

So for a simplistic example my first script is,

first.py
x = 5
import second

and my second script is,

second.py 
print x

and I would expect it to print x but I get

NameError: name 'x' is not defined

I'm not sure if import is right way to achieve this, but if someone could shed light on it in a simple way that would be great!

thanks,


EDIT

After reading the comments I thought I would expand on my question. Aswin Murugesh answer fixes the import problem I was having, however the solution does not have the desired outcome as I can not seem to pass items in a list this way.

In first.py I have a list which I process as follows

for insert, (list) in enumerate(list, start =1):
    'call second.py passing current list item'

I wanted to pass each item in the list to a second python file for further processing (web scraping), I didn't want to do this in first.py as this is meant to be the main 'scan' program which then calls other programs. I hope this now make more sense.

Thanks for the comments thus far.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you call a script, the calling script can access the namespace of the called script. (In your case, first can access the namespace of second.) However, what you are asking for is the other way around. Your variable is defined in the calling script, and you want the called script to access the caller's namespace.

An answer is already stated in this SO post, in the question itself:

Access namespace of calling module

But I will just explain it here in your context.

To get what you want in your case, start off the called script with the following line:

from __main__ import *

This allows it to access the namespace (all variables and functions) of the caller script.

So now your calling script is, as before:

x=5
import second

and the called script is:

from __main__ import *
print x

This should work fine.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...