[英]Is there a way to add arguments as variables to execute a command line instruction from inside a python file
我有一個文件 buyfruits.py,它解析 arguments 並將它們發送到一個名為 buy.py 的文件,例如這個命令: $python buyfruits.py --quantity 20 --amount 50 --fruit apple
將導致用 50 個硬幣購買 20 個蘋果
我希望這個從另一個文件中獲取 arguments
比方說 input.py
amt = input("Enter amount ")
q = input("Enter quantity you want")
what = input("Enter fruit you want to buy ")
我希望這個 input.py 文件執行這段代碼
$python buyfruits.py --quantity q --amount amt --fruit 什么
使用 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))
或者子進程,如果要捕獲buyfruits.py的output:
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
閱讀有關 python子進程模塊的信息。
#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)
你也可以使用 call,check_call 。
你可以使用 getopt 和 sys 庫
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()
輸入:
$python file_1.py -a 20 -q 5 -f 蘋果
output:
數量:20
數量:5
水果:蘋果
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.