1

Let's say I have a Python script named script1.py that has the following code:

import sys
name = sys.argv[1]
print("Bye", name)

And a second Python script script2.py that calls the first one:

import sys
name = sys.argv[1]
print("Hello", name)
import script1

How can I pass an argument from the second script to the first one, as in the given examples?

I'd like the output to look like this when I run my script from the terminal:

>> python script2.py Bob
Hello Bob
Bye Bob
2
  • 1
    I would use a callback function that returns your desired value Commented Mar 7, 2018 at 17:36
  • You're right vaultah. I hadn't realised that the parameters where share by both scripts. Thanks! Commented Mar 7, 2018 at 17:55

1 Answer 1

2

A couple of options the way you're doing it (although your example does actually work right now because sys.argv is the same for both scripts but won't in the generic case where you want to pass generic arguments).

Use os.system

import os
os.system('python script1.py {}'.format(name))

Use subprocess

import subprocess
subprocess.Popen(['python', 'script1.py', name])

A better way, IMO, would be to make script 1's logic into a function

# script1.py
import sys

def bye(name):
    print("Bye", name)

if __name__ == '__main__':   # will only run when script1.py is run directly
    bye(sys.argv[1])

and then in script2.py do

# script2.py
import sys
import script1

name = sys.argv[1]
print("Hello", name)
script1.bye(name)
Sign up to request clarification or add additional context in comments.

2 Comments

The thing is that the script1.py logic is much complicate than the one shown here. That's why I didn't want to put the logic into a function, but you are right, that must be the best solution. Thanks!
In general, don't write python like you'd write a bash script. Always put the logic in a main function or something and then use the if __name__ == '__main__': trick. If this worked, could you please accept the answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.