Python send variable to another file

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.

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    When the lines of code increase, it is cumbersome to search for the required block of code. It is a good practice to differentiate the lines of code according to their working. It can be done by having separate files for different working codes. As we know, various libraries in Python provide various methods and variables that we access using simple import <library_name>. For example, math library. If we want to use the pi variable we use import math and then math.pi.

    To import variables from another file, we have to import that file from the current program. This will provide access to all the methods and variables available in that file.

    The import statement

    We can use any Python source file as a module by executing an import statement in some other Python source file. When the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the interpreter searches for importing a module.

    The from import Statement

    Python’s from statement lets you import specific attributes from a module. 

    Note: For more information, refer Python Modules

    Different approaches to import variables from other file

    • import <file_name> and then use <file_name>.<variable_name> to access variable
    • from <file_name> import <variable_names> and use variables
    • from <file_name> import * and then use variables directly.

    Example:

    Suppose we have a file named “swaps.py”. We have to import the x and y variable from this file in another file named “calval.py”. 

    Python3

    x = 23

    y = 30

    def swapVal(x, y):

      x,y = y,x

      return x, y

    Now create a second python file to call the variable from the above code:

    Python3

    import swaps

    new_x = swaps.x

    new_y = swaps.y

    print("x value: ", new_x, "y value:", new_y)

    x , y = swaps.swapVal(new_x,new_y)

    print("x value: ", x, "y value:", y)

    Output:

    x value:  23 y value: 30
    x value:  30 y value: 23

    Python send variable to another file

    Learn how to create global variables that can be shared between files/modules in Python.


    Global variables are used in programming to share memory between different sections of an application, this allows for a range of functionality such as keeping track of resource use between classes, storing statistics about an application and much more. In Python, they are mainly used to share values between classes and functions.

    Understanding global variables in Python

    In Python, a conventional global variable is only used to share a value within classes and functions. A variable- once declared as a global within a function or class can then be modified within the segment.

    num = 1 
     
    def increment(): 
        global num 
        num += 1 
    

    The above code would allow the variable 'num' to be used within that function, whereas if you were to omit the global statement, it would be undefined.

    If you were to attempt to use this logic to declare a global variable from another class however, it would not work as it would in other languages such as Java or C++.

    For example, if we had one class with a variable that needed to be accessed from within another imported class, there would be no way for us to access this variable using the global keyword:

    main.py

    import test 
     
    num = 1 
     
    test.increment() 
    

    test.py

    def increment(): 
        global num 
        num += 1 
    

    As you can see above, even though we try to access 'num' as a global within the increment() function after it has been given a value in main.py, it will still not be defined and will result in an error.

    Sharing global variables between files/modules in Python

    Even though the global keyword is conventionally only used to access variables from within the same module, there are ways to use it in order to share variables between files. For example, we could take influence from PHP and create something similar to the "superglobals" variables.

    To do this, you can create a new module specifically for storing all the global variables your application might need. For this you can create a function that will initialize any of these globals with a default value, you only need to call this function once from your main class, then you can import the globals file from any other class and use those globals as needed.

    For example, let's create a function similar to the example above that will increment a global variable. For this we'll need 3 classes to prove the concept; a main class, a class containing our increment function and a class containing the globals.

    globals.py

    def initialize(): 
        global num 
        num = 1 
    

    main.py

    import globals 
    import test 
     
    if __name__ == "__main__": 
        globals.initialize() 
        print( globals.num ) 
        test.increment() 
        print( globals.num ) 
    

    test.py

    import globals 
       
    def increment(): 
        globals.num += 1
    

    When we run main.py the output will be:

    1 
    2 
    

    As you can see, once we've initialized the global variable in globals.py, we can then access 'num' as a property from any other module within the application and it will retain its value.

    If you're having trouble understanding how this works, feel free to leave a comment below!


    How do you pass a variable to another file in Python?

    To import variables from another file, we have to import that file from the current program..
    import <file_name> and then use <file_name>.<variable_name> to access variable..
    from <file_name> import <variable_names> and use variables..
    from <file_name> import * and then use variables directly..

    How do I pass a value from one Python script to another?

    Steps to Run One Python Script From Another.
    Step 1: Place the Python Scripts in the Same Folder. To start, place your Python scripts in the same folder. ... .
    Step 2: Add the Syntax. Next, add the syntax to each of your scripts. ... .
    Step 3: Run One Python Script From Another..

    How do you transfer data between files in Python?

    you can use multiprocessing module to implement a Pipe between the two modules. Then you can start one of the modules as a Process and use the Pipe to communicate with it. The best part about using pipes is you can also pass python objects like dict,list through it.

    What is if name == Main in Python?

    Syntactically, Python's if __name__ == "__main__" idiom is just a normal conditional block: 1if __name__ == "__main__": 2 ... The indented block starting in line 2 contains all the code that Python will execute when the conditional statement in line 1 evaluates to True .