Pass argument into another script and then return back computed value

Viewed 59

I have two python script test1 and test2. If I hit ctrl+B in sublime under test1.py, the expected output should be 7770 and 8880

test1.py

import subprocess
import test2


subprocess.call(["python", "test2.py","777"]) #subprocess.call compulsory
print(test2.b) #8880 from test2

test2.py

import sys

a = sys.argv[1]
a = a * 10
print(a) #7770

'''
after some calculation
'''

#now return some number back to test1.py
b = 8880

How would I selectively get b only back to test1? Tried from test2 import b, it did not work. It attempt to bring in a too, that caused the problem.

Log:

Traceback (most recent call last):
  File ".....\test1.py", line 2, in <module>
      import test2
  File "......\test2.py", line 3, in <module>
      a = sys.argv[1]
IndexError: list index out of range
1 Answers

Executing test2.py as subpprocess and importing test2.py are two completely different things. They both will use their own memory and access / modify their own versions of b.

So what you try to describe in test1.py cannot be done this way.

You have to choose different ways:

Either you do not use subprocesses and work only with python imports or you call test2.py and parse the output of test2.py (The output of print)

As I don't know what you really try to achieve this example might be off.

test1.py:

import subprocess
import test2

cmd = ["python", "test2.py", "777"]
print("CMD", cmd)
rslt = subprocess.run(cmd, stdout=subprocess.PIPE) #subprocess.call compulsory
print("STDOUT=", repr(rslt.stdout))
value = int(rslt.stdout)
test2.b = value
print(test2.b) #8880 from test2

test2.py:

import sys

b = 0

if __name__ == "__main__":
    # do not execute if being imported
    a = sys.argv[1]
    a = a * 10
    # print(a) #7770  # do not print here just print b

    '''
    after some calculation
    '''

    #now return some number back to test1.py
    b = 8880
    print(b)
    ```
Related