I have two files and needed to move a variable from one to the other. There is also some shell scripting involved. For example, I have script1.py and a variable called var1.
script1.py
var1 = sys.argv[1]
When I try to import this into another Python file. For e.g.
script2.py
from script1.py import var1
print(var1)
It is actually running the sys.argv[1] again in script2.py. This is how my shell script looks.
shellcode.sh
python3 script1.py "1st parameter"
python3 script2.py "2nd"
How to get only the "1st parameter" not "2nd". I'm a complete beginner at python and shell scripting. Is it related to pass by value? Any help would be highly appreciated.
CodePudding user response:
pass directly arguments from script2.py
it should work.
script1.py
import sys
var1 = sys.argv[1]
in script2.py
from script1 import var1
print(var1)
on shell run like this
python3 script2.py --test
Will print #
test
CodePudding user response:
One way around this would be to use the parameter as a variable in your shell script and just pass both to the second python argument.
shellcode.sh:
#!/bin/bash
PAR1="1st paramter"
PAR2="2nd parmaeter"
python3 script1.py $PAR1
python3 script2.py $PAR1 $PAR2
Otherwise you could write and read the argument something like
script1.py:
import sys
var1 = sys.argv[1]
with open('script1_var.txt', 'w') as f:
f.write(var1)
script2.py:
import sys
with open('script1_var.txt', 'r') as f:
var1 = f.readlines()[0].strip()
var2 = sys.argv[1]
print('var1', var1)
print('var2', var2)