Python Source with subprocess

I'm trying to run a command line in the terminal through a python script. The command line is as follows:

vcftools --vcf <arquivo.vcf> --extract-FORMAT-info GT --out <arquivo sem extensão>

For this I have the following lines:

import os
import subprocess
import getopt
import sys

def main(argv):
    inputfile_1 = ''
    outputfile = ''
    try:
        opts, args = getopt.getopt(
            argv, "hi:o:", ["ifile=", "ofile="])
    except getopt.GetoptError:
        print ('test.py -i <inputfile_1> -o <outputfile>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print ('test.py -i <inputfile_1> -o <outputfile>')
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile_1 = arg
        elif opt in ("-o", "--ofile"):
            outputfile = arg
    print ('O arquivo de input i: %s' % (inputfile_1))
    print ('O arquivo de output: %s' % (outputfile))

if __name__ == "__main__":
    main(sys.argv[1:])


proc = subprocess.Popen(["vcftools --vcf" + inputfile_1 + "--extract-FORMAT-info GT --out" + outputfile], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()

And the error I'm getting:

guido-5:vcfx_statistics_gvcf_herc2 debortoli$ python vcftools.py -i herc2.gvcf.statistics_checkad.vcf -o test_vcf_ad

O arquivo de input i: herc2.gvcf.statistics_checkad.vcf
O arquivo de output: test_vcf_ad

Traceback (most recent call last):
      File "vcftools.py", line 30, in <module>
        proc = subprocess.Popen(["vcftools --vcf" + inputfile_1 + "--extract-FORMAT-info GT --out" + outputfile], stdout=subprocess.PIPE, shell=True)
    NameError: name 'inputfile_1' is not defined

By the way the error is in the assignment of inputfile_1 to sys.argv[1]...

Any help will be welcome.

Author: guidebortoli, 2017-03-15

1 answers

The problem is that the variable inputfile_1 you use in subprocess.Popen was defined only in the scope of the main definition. To work you would only need to declare it as global or put this snippet of code within the scope of the main definition.

 1
Author: Giuliana Bezerra, 2017-03-15 18:06:00