Python Source with subprocess

Asked

Viewed 163 times

0

I’m trying to run a command line on 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 mistake 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

Apparently the error is in the attribution of inputfile_1 at the sys.argv[1]...

Any help would be welcome.

  • 1

    The tau variable input_file1 is only visible inside the main function, you must proc=... also inside this, at the end maybe

1 answer

1


The problem is that the variable inputfile_1 that 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 place this code snippet within the scope of the main definition.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.