简体   繁体   中英

Is there a way to add arguments as variables to execute a command line instruction from inside a python file

I have a file buyfruits.py this parses the arguments and sends them to a file called buying.py for eg this command: $python buyfruits.py --quantity 20 --amount 50 --fruit apple

will result in buy 20 apples for 50 coins

I want this to take arguments from another file

let's say input.py

amt = input("Enter amount ")
q = input("Enter quantity you want")
what = input("Enter fruit you want to buy ")

i want this input.py file to execute this code

$python buyfruits.py --quantity q --amount amt --fruit what

Use os.system:

import os

amt = input("Enter amount ")
q = input("Enter quantity you want")
what = input("Enter fruit you want to buy ")

os.system("buyfruits.py --quantity %s --amount %s --fruit %s" % (q, amt, what))

or subprocess, if you want to capture the output of buyfruits.py:

import subprocess, shlex # shlex needed for command-line splitting

amt = input("Enter amount ")
q = input("Enter quantity you want")
what = input("Enter fruit you want to buy ")

p = subprocess.Popen(shlex.split("buyfruits.py --quantity %s --amount %s --fruit %s" % (q, amt, what)))
print("output : %s\nerrors : %s" % p.communicate()) # print output and errors of the process

Read about python subprocess module.

#I assume you are using Python3.x
import subprocess
amt = input("Enter amount ")
q = input("Enter quantity you want")
what = input("Enter fruit you want to buy ")
output=subprocess.check_output(['buyfruits.py', '--quantity', q, '--amount', amt, '--fruit', what], shell=True)
print(output)

you can use call,check_call as well.

you can use getopt and sys libraries

import getopt, sys
def get_arguments():
    fruit = None
    quantity = None
    amount = None
    argv = sys.argv[1:]
    opts, argv = getopt.getopt(argv, "a:q:f:")
    for opt, argv in opts:
        if opt in ['-a']:
            amount = argv
        elif opt in ['-q']:
            quantity = argv
        elif opt in ['-f']:
            fruit = argv
            
    print('amount : {}'.format(amount))
    print('quantity : {}'.format(quantity))
    print('fruit : {}'.format(fruit))

get_arguments()

input:

$python file_1.py -a 20 -q 5 -f apple

output:

amount: 20
quantity: 5
fruit: apple

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