Run command line containing multiple strings from

2019-08-20 05:11发布

Hello i am trying to autogenerate a PDF, i have made a python script that generates the wanted PDF but to generate it i have to call my_cover.py -s "Atsumi" -t "GE1.5s" -co "Japan" from my command line.

Does anyone know an easy way to call this command line from within my python script. In the script i will prompt the user to input the 3 strings which currently are "Atsumi", "GE1.5s" and "Japan" but these should change with whatever the user inputs and should therefore also change in the command line call. Any help is much appreciated

site_name = raw_input('Name of wind turbine site: ')
turbine_name = raw_input('Name of turbine type: ')
country_name = raw_input('Name of country location: ')

parser = argparse.ArgumentParser()
parser.add_argument('-s', '--site')
parser.add_argument('-t', '--turbine')
parser.add_argument('-c', '--country') 

args = parser.parse_args()

with open('cover.tex','w') as f:
    f.write(content%args.__dict__)

cmd = ['pdflatex', '-interaction', 'nonstopmode', 'cover.tex']
proc = subprocess.Popen(cmd)
proc.communicate()

retcode = proc.returncode
if not retcode == 0:
    os.unlink('cover.pdf')
    raise ValueError('Error {} executing command: {}'.format(retcode, ' '.join(cmd))) 

os.unlink('cover.tex')
os.unlink('cover.log')

"Code to run the command line goes here"
'''my_cover.py -s "Atsumi" -t "GE1.5s" -co "Japan"'''

1条回答
三岁会撩人
2楼-- · 2019-08-20 05:29

docopt is a great way to do program interfaces, but it would encourage syntax like cover.py --country=Japan --site=Atsumi --turbine=GE15.s (if you want flags).

In my experience docopt makes you rethink your program ideology, what it does and how to achive this. For example, you can experiment with calls like

cover.py cover.pdf --country=Japan --site=Atsumi --turbine=GE15.s
cover.py Japan Atsumi GE15.s

It seems your pdf gerenation is taken care of, but I'd also suggest:

  • get rid on raw_input(), if you can - you are having the command line args anyways
  • split script to functions that do one thing, eg preparing a tex file and writing a pdf file
  • take a use of if __name__ == '__main__':
查看更多
登录 后发表回答