Fernando S. Peregrino
Fernando S. Peregrino

Reputation: 515

Call a Python script with parameters from a Python script

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

Upvotes: 1

Views: 5626

Answers (1)

FHTMitchell
FHTMitchell

Reputation: 12147

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)

Upvotes: 2

Related Questions