Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
errors : %s" % p.communicate()) # print output and errors of the process

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...