运行包含来自python脚本的多个字符串的命令行 [英] Run command line containing multiple strings from python script

查看:153
本文介绍了运行包含来自python脚本的多个字符串的命令行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在尝试自动生成PDF,我制作了一个Python脚本来生成所需的PDF,但是要生成它,我必须调用 my_cover.py -s Atsumi -t GE1。 5s -co Japan 从我的命令行中。

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.

有人知道从我的python脚本中调用此命令行的简单方法吗? 。在脚本中,我将提示用户输入3个字符串,它们分别是 Atsumi, GE1.5s和 Japan,但这些字符串应随用户输入的内容而变化,因此也应在命令行调用中进行更改。非常感谢您的帮助

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"'''


推荐答案

docopt 是执行程序接口的好方法,但它会鼓励 cover.py --country =日本--site = Atsumi --turbine = GE15.s (如果您需要标志)。

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

根据我的经验, docopt 使您重新思考程序的思想,它的作用以及如何实现这一目标。例如,您可以尝试使用

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

pdf修正了问题,但我还建议:

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


  • 摆脱 raw_input()(如果可以)-无论如何,您都在使用命令行args

  • 将脚本拆分为执行某项功能的函数,例如,准备tex文件并编写pdf文件

  • 如果__name__ =='__main __':

  • 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__':

这篇关于运行包含来自python脚本的多个字符串的命令行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆