How do I pass a variable into a subprocess run command?

Viewed 118

I have the following python script:

import os

with open(os.path.join(cwd_path,"script_log.txt"), 'a') as script_log:
        script_log.write(variable_name)

I'd like to run this script from another file. Something like this:

from subprocess import run
run(["Python", "{}".format('test2_text.py'), variable_name='Variable Name Success'])

So that I can run the file with that variable input. This seems like a simple process but I can't seem to find a way to do it. I'm a beginner to the subprocess functions.

1 Answers

You can pass your variable as a command line argument to test2_text.py script.

Change test2_text.py to:

import os
import sys

# get the first argument provided to the script
variable_name = sys.argv[1] 

with open(os.path.join(cwd_path,"script_log.txt"), 'a') as script_log:
        script_log.write(variable_name)

and then you can run it from another script:

from subprocess import run
variable_name = 'Variable Name Success'
run(["Python", "test2_text.py", variable_name])
Related