简体   繁体   中英

Run a python script from another python script and pass variables to it

There are some similar questions that are asked; but, either the answers didn't cover a specific part that is a key point for me or I just couldn't understand. So, let me explain my question:

I want to create 3 python scripts. Let's call them p1.py, p2.py and p3.py . When I run p1, it will gather the time information with

import datetime    
captureTime = datetime.datetime.now()

then it will change the format of the date and store it with a variable as shown below

folderName = captureTime.strftime('%Y-%m-%d-%H-%M-%S')

Then, it will create a folder named by the value of the string 'folderName'.

After this part, I don't know what to do.

p1 should run p2 and p3, and pass the value of 'folderName' to them, then stop; and, p2 and p3 should create files under the folder named by the value of 'folderName'.

Thank you.

In p1:

import p2
args = ['foo', bar]
p2.main(args)

In p2:

def main(args): 
    do_whatever()

if __name__ == '__main__':
  main()

p3 will be of a similar structure to p2

You can make use of the subprocess module do perform external commands. It is best to start with much simpler commands first to get the gist of it all. Below is a dummy example:

import subprocess
from subprocess import PIPE

def main():
    process = subprocess.Popen('echo %USERNAME%', stdout=PIPE, shell=True)
    username = process.communicate()[0]
    print username #prints the username of the account you're logged in as

    process = subprocess.call('python py1.py --help', shell=True)
    process = subprocess.call('python py2.py --help', shell=True)
    process = subprocess.call('python py3.py --help', shell=True)

if __name__ == '__main__':
    main()

This will grab the output from echo %USERNAME% and store it. It will also run your three scripts but do nothing fancy with them. You can PIPE the output of the scripts as shown in the first example and feed them back in to your next script.

This is NOT the only way to do this (you can import your other scripts). This is nice if you would like to have an external master script to control and manipulate all your child scripts.

If you haven't checked our argparse yet, you should.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM