有没有办法将参数添加为变量以从 python 文件中执行命令行指令

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

我有一个文件 buyfruits.py 这会解析参数并将它们发送到名为 buying.py 的文件 例如这个命令: $python buyfruits.py --quantity 20 --amount 50 --fruit apple

将导致用 50 个金币买 20 个苹果

我希望它从另一个文件中获取参数

假设 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 what

使用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的输出:

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 subprocess 模块。

#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)

你也可以打电话,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 apple

输出:

amount : 20
quantity : 5
fruit : apple