1

I am a beginner -- I am trying to write a Main py program that references a py script, passing data arguments to the Script; and then, receiving back data from the Script. What follows is my initial code (that does NOT work) -- your help will be very much appreciated. Thank U.

main.py

  1. Main Program

  2. import scriptNo1
  3. import sys
  4. print("Start Main program")
  5. arg1 = 3
  6. arg2 = 5
  7. scriptNo1[arg1, arg2]
  8. sys.argv = ['scriptNo1.py', 'arg1', 'arg2']
  9. val1 = scriptNo1.passBackVal
  10. print(arg1, arg2, val1)
  11. print("The end")
  12. quit()

scriptNo1.py

  1. Script Program to be used by Main Program

  2. import sys
  3. print("Start Script program")
  4. passBackVal = arg1 + arg2
  5. print("passBackVal in script is: ", passBackVal)
  6. print("End of Script program")
  • I have a question: why don't you create a method in scriptNo1.py and import it inside main.py? That way, you can call it with the args you want. – Paulo Jun 18 '22 at 22:07
  • You have taught me something new -- I have NO awareness of Methods --something new to learn. Thank U – Paul Kostro Jun 18 '22 at 22:31

2 Answers2

0

An idea:

#main.py
from scriptNo1 import func
import sys
ans = func(sys.argv[1], sys.argv[2])
print(sys.argv[1], sys.argv[2], ans)

#scriptNo1.py
def func(a, b):
    return a + b

Is it what you want?

Paulo
  • 1,458
  • 2
  • 12
  • 26
0

This is my final outcome (Thank U @Paulo and @Tomerikoo):

# main.py
import scriptNo1
from scriptNo1 import funcNo1
arg1 = 3
arg2 = 5
argv = []
argv.append(arg1)
argv.append(arg2)
ans = func(argv[0], argv[1])
print(argv[0], argv[1], ans)
quit()

and

# scriptNo1.py
def funcNo1(a, b):
    x = a + b
    y = "cat"
    z = 123.456
    passBackVal = [x, y, z]
    return passBackVal
  • That is a very strange use of `sys.argv`. It is meant to be used for command line arguments. If you use it like that, why not just use a list? Or not use it at all? Just do `ans = func(arg1, arg2)` – Tomerikoo Jun 19 '22 at 14:46
  • Thank U @Tomerikoo -- when you are a beginner (like I am) the comments from experts are VERY valuable. The recommendation is being implemented. Thank U. – Paul Kostro Jun 19 '22 at 18:40
  • No problem at all. As I said before, note that the list is not very necessary in this case. Any instance of `argv[0]` can be replaced with `arg1` and any instance of `argv[1]` can be replaced with `arg2`. The list just takes up unnecessary memory. Another comment, you should only use one kind of import: either do `import script` and then call the function `script.func(...)` ; or `from script import func` and then just `func(...)`. See [Use 'import module' or 'from module import'?](https://stackoverflow.com/q/710551/6045800) for more – Tomerikoo Jun 20 '22 at 05:59