简体   繁体   English

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

[英]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我有一个文件 buyfruits.py,它解析 arguments 并将它们发送到一个名为 buy.py 的文件,例如这个命令: $python buyfruits.py --quantity 20 --amount 50 --fruit apple

will result in buy 20 apples for 50 coins将导致用 50 个硬币购买 20 个苹果

I want this to take arguments from another file我希望这个从另一个文件中获取 arguments

let's say input.py比方说 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我希望这个 input.py 文件执行这段代码

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

Use os.system:使用 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:或者子进程,如果要捕获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

Read about python subprocess module.阅读有关 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)

you can use call,check_call as well.你也可以使用 call,check_call 。

you can use getopt and sys libraries你可以使用 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()

input:输入:

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

output: output:

amount: 20数量:20
quantity: 5数量:5
fruit: apple水果:苹果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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